Python,一个热编码器的修改版本



>我需要帮助将多个列(例如 a1 和 a2 列(中的唯一值转换为新列,然后相应地将列 b1 和 b2 中的值分配给这些新创建的列。

例如,如果我有一个数据框 df,如下所示:

import pandas as pd
import numpy as np
df = pd.DataFrame({'a1':['q','w','e','r'], 'a2':['s','e','q','u'], 'b1':[1,2,3,4], 'b2':[5,6,7,8],})
print(df)
a1 a2  b1  b2
0  q  s   1   5
1  w  e   2   6
2  e  q   3   7
3  r  u   4   8

列 a1 和 a2 的唯一值是 ['e', 'q', 'r', 's', 'u', 'w']。

np.unique(df.loc[:,['a1','a2']].values)
array(['e', 'q', 'r', 's', 'u', 'w'], dtype=object)

我想将 df 转换为新的数据帧 df1,如下所示:

print(df1)
e  q  r  s  u  w
0  0  1  0  5  0  0
1  6  0  0  0  0  2
2  3  7  0  0  0  0
3  0  0  4  0  8  0

请注意,"q"和"s"出现在 df 的第一行中,因此 1(来自列 b1(和 5(来自列 b2(被分配给数据帧 df1 的 q 和 s 列,而其他列为 0。

我本可以在 R 中使用 melt 和 dcast 函数来实现这一点,但我不确定如何在 Python 中做到这一点。

谢谢。

import pandas as pd
df = pd.DataFrame({'a1':['q','w','e','r'], 'a2':['s','e','q','u'], 'b1':[1,2,3,4], 'b2':[5,6,7,8],})
pd.DataFrame.from_dict([dict(zip(df.iloc[t,:2] , df.iloc[t,2:])) for t in range(len(df))]).fillna(0).astype(int)
e   q   r   s   u   w
0   0   1   0   5   0   0
1   6   0   0   0   0   2
2   3   7   0   0   0   0
3   0   0   4   0   8   0

最新更新