我有以下数据框...
idx Group key value Time IsTrue
1 bicycle person yes 9:30 yes
2 bicycle name bob 9:30 yes
3 bicycle alive yes 9:30 yes
5 non-cycle person no 1:30 no
6 non-cycle name jack 1:30 no
我想要从数据框中得到以下结果
idx Group Time IsTrue person name alive
1 bicycle 9:30 yes yes bob yes
2 non-cycle 1:30 no no jack NA
其中键列成为新列,值是这些新列的行。除了键和值列之外,所有其他行始终具有相同的值。按键会改变,所以我想要一些动态的东西。
我当前的解决方案使用 pandas groupby & apply (基于 Group 列),并为每个组创建一个新的数据框,但这似乎过度设计。有没有更简单的解决方案?
最佳答案
编辑:
当你固定输出时。我使用 set_index
和 unstack
df.set_index(['Group', 'Time', 'IsTrue', 'key'])['value'].unstack().reset_index()
Out[503]:
key Group Time IsTrue alive name person
0 bicycle 9:30 yes yes bob yes
1 non-cycle 1:30 no NaN jack no
原文:
您想要的输出令人困惑。如果这是您想要的,让我们尝试一下这个解决方案。如果不是的话我就删除
df.pivot_table(index=['Group', 'Time', 'IsTrue'], columns='key', values='value', aggfunc='first').reset_index()
Out[487]:
key Group Time IsTrue alive name person
0 bicycle 9:30 yes yes bob yes
1 non-cycle 1:30 no NaN jack no
关于python - 将行转置为列,同时根据组展平数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58090277/