python-3.x - 如何制作跨多个列的 Pandas 框架值,其列

标签 python-3.x pandas dataframe

我在 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/

相关文章:

python - Pandas,根据列值的唯一子集追加列

python - 我想从带有字符串的列表中提取数字

python - 错误: AttributeError: 'Application' object has no attribute 'message'

python - statsmodels 无法使用诸如登录异构类型行之类的函数来预测公式

python - 使用 Python 从列表中的货币值中删除标点符号

python - 如何有效访问 Pandas 中满足条件的第一个和最后一个出现的索引

python - 为列赋值时矛盾的 pandas.DataFrame 行为

python - Python套接字发送/接收逐渐变慢

linux - 在 virtualnev 中安装 Pyhunspell

python - 日期滚动总和指数