我有一个DataFrames列表,我想对某些列进行一次热编码。例如,如果:
In[1]: df1 = pd.DataFrame(np.array([['a', 'a'], ['b', 'b'], ['c', 'c']]),
columns=['col_1', 'col_2'])
df2 = pd.DataFrame(np.array([['a', 'a'], ['b', 'b'], ['c', 'c']]),
columns=['col_1', 'col_2'])
combined = [df1, df2]
combined
Out[1]: col_1 col_2
0 a a
1 b b
2 c c
我目前正在使用以下方法。
In[2]: for df in combined:
one_hot = pd.get_dummies(df["col_2"])
df[one_hot.columns] = one_hot
df.drop("col_2", axis=1, inplace=True)
df1
Out[2]: col_1 a b c
0 a 1 0 0
1 b 0 1 0
2 c 0 0 1
我是否缺少更简洁的解决方案?
编辑
一个重要的要求是我需要修改原始数据框。
最佳答案
OP的方法很好
for df in combined:
one_hot = pd.get_dummies(df["col_2"])
df[one_hot.columns] = one_hot
df.drop("col_2", axis=1, inplace=True)
重新分配给所有名称
df1, df2 = [df.join(pd.get_dummies(df['col_2'])).drop('col_2', 1) for df in combined]
关于python - 多个Pandas DataFrame的get_dummies(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56151188/