如何在 python 中以基于行的方式对列表值进行热编码?
How to one hot encode list values on row based way in python?
为了解释我想做什么,我展示了这个例子。
起初,我的数据是这样的。
数据 1)
A 列:0、1、2(共 3 类)
B 列:0、1、2(共 3 类)
A B
1 1
0 0
2 1
然后我对 A 列和 B 列进行了一次热编码。
one-hot编码后,我的数据是这样的。
数据2)
Index col1 col2 col3 col4 col5 col6
0 0 1 0 0 1 0
1 1 0 0 1 0 0
2 0 0 1 1 0 0
假设我有很多数据,比如 data2。
然后,我想对数据帧 data2 进行一次热编码。
在这种情况下,索引 0、1、2 的值在 data2 中彼此不同。
所以如果我对 data2 进行一次热编码,那么我的结果应该是
数据3)
Index col1 col2 col3
0 1 0 0
1 0 1 0
2 0 0 1
像这样。
如何在 python 中执行此操作?
换句话说,我想对 dataframe
中的每个元素进行一次热编码
如果你想对各种可能的行序列进行编码,你可以这样做:
import pandas as pd
df=pd.DataFrame({'A':[1,0,2],'B':[1,0,1]})
In [40]: df
Out[40]:
A B
0 1 1
1 0 0
2 2 1
A_oh = pd.get_dummies(df.A,prefix='A')
B_oh = pd.get_dummies(df.B,prefix='B')
df_oh = pd.concat([A_oh,B_oh],axis=1)
In [41]: df_oh
Out[41]:
A_0 A_1 A_2 B_0 B_1
0 0 1 0 0 1
1 1 0 0 1 0
2 0 0 1 0 1
df_concat = df_oh.apply(lambda r:str(''.join(str(r[col]) for col in df_oh.columns)),axis=1)
df_concat
Out[37]:
0 01001
1 10010
2 00101
dtype: object
pd.get_dummies(df_concat)
Out[39]:
00101 01001 10010
0 0 1 0
1 0 0 1
2 1 0 0
为了解释我想做什么,我展示了这个例子。
起初,我的数据是这样的。
数据 1)
A 列:0、1、2(共 3 类)
B 列:0、1、2(共 3 类)
A B
1 1
0 0
2 1
然后我对 A 列和 B 列进行了一次热编码。 one-hot编码后,我的数据是这样的。
数据2)
Index col1 col2 col3 col4 col5 col6
0 0 1 0 0 1 0
1 1 0 0 1 0 0
2 0 0 1 1 0 0
假设我有很多数据,比如 data2。 然后,我想对数据帧 data2 进行一次热编码。 在这种情况下,索引 0、1、2 的值在 data2 中彼此不同。 所以如果我对 data2 进行一次热编码,那么我的结果应该是
数据3)
Index col1 col2 col3
0 1 0 0
1 0 1 0
2 0 0 1
像这样。
如何在 python 中执行此操作? 换句话说,我想对 dataframe
中的每个元素进行一次热编码如果你想对各种可能的行序列进行编码,你可以这样做:
import pandas as pd
df=pd.DataFrame({'A':[1,0,2],'B':[1,0,1]})
In [40]: df
Out[40]:
A B
0 1 1
1 0 0
2 2 1
A_oh = pd.get_dummies(df.A,prefix='A')
B_oh = pd.get_dummies(df.B,prefix='B')
df_oh = pd.concat([A_oh,B_oh],axis=1)
In [41]: df_oh
Out[41]:
A_0 A_1 A_2 B_0 B_1
0 0 1 0 0 1
1 1 0 0 1 0
2 0 0 1 0 1
df_concat = df_oh.apply(lambda r:str(''.join(str(r[col]) for col in df_oh.columns)),axis=1)
df_concat
Out[37]:
0 01001
1 10010
2 00101
dtype: object
pd.get_dummies(df_concat)
Out[39]:
00101 01001 10010
0 0 1 0
1 0 0 1
2 1 0 0