我在 Pandas 中加载了以下数据框。
打印(pandaDf)
id col1 col2 col3
12a a b b d
22b d a b
33c c a b
我正在尝试将多行中的值转换为其列,因此输出将如下所示:
期望的输出:
id a b c d
12a 1 1 0 1
22b 1 1 0 0
33c 1 1 1 0
我尝试添加一个值 = 1 的值列并使用数据透视表
pandaDf['值'] = 1
列 = ['col1', 'col2', 'col3']
pandaDf.pivot_table(index = 'id', value = 'value', columns = 列)
但是,生成的数据框是多级索引,并且 pandaDf.pivot() 方法不允许多个列值。
请告知我如何使用单级索引的输出来做到这一点。
感谢您花时间阅读本文,如果我在发布问题时出现任何格式错误,我深表歉意。我仍在学习正确的 stackoverflow 语法。
最佳答案
可以使用One-Hot Encoding来解决这个问题。
这是执行此操作的一种方法 pd.get_dummies
以及一些多索引展平和 sum
:
df1 = df.set_index('id')
df_out = pd.get_dummies(df1)
df_out.columns = df_out.columns.str.split('_', expand=True)
df_out = df_out.sum(level=1, axis=1).reset_index()
print(df_out)
输出:
id a c d b
0 12a 1 0 1 1
1 22b 1 0 1 1
2 33c 1 1 0 1
关于python-3.x - 如何制作跨多个列的 Pandas 框架值,其列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51316000/