How can one hot encode one pandas dataframe column?

I am trying single-hot to encode a single column of data.

enc = OneHotEncoder()
minitable = enc.fit_transform(df["ids"])

But I get

Deprecated Warning: Passing the 1st array as stale data at 0.17 and willraise ValueError at 0.19.

Is there a workaround for this?

+4
source share
1 answer

I think you can use get_dummies:

df = pd.DataFrame({'ids':['a','b','c']})

print (df)
  ids
0   a
1   b
2   c

print (df.ids.str.get_dummies())
   a  b  c
0  1  0  0
1  0  1  0
2  0  0  1

EDIT:

If the input column is c lists, first select str, delete []with stripand call get_dummies:

df = pd.DataFrame({'ids':[[0,4,5],[4,7,8],[5,1,2]]})

print(df)
         ids
0  [0, 4, 5]
1  [4, 7, 8]
2  [5, 1, 2]

print (df.ids.astype(str).str.strip('[]').str.get_dummies(', '))
   0  1  2  4  5  7  8
0  1  0  0  1  1  0  0
1  0  0  0  1  0  1  1
2  0  1  1  0  1  0  0
+6
source

Source: https://habr.com/ru/post/1663961/


All Articles