Python Pandas将多列数据行转换为列

7

我有一个包含多个列的DF,我想将其从行转换为列,大多数在stackoverflow上看到的解决方案只涉及两列

来自DF

PO ID   PO Name Region  Date    Price
1       AA      North   07/2016 100
2       BB      South   07/2016 200
1       AA      North   08/2016 300
2       BB      South   08/2016 400
1       AA      North   09/2016 500

To DF

PO ID   PO Name Region  07/2016 08/2016 09/2016
1       AA      North   100     300     500
2       BB      South   200     400     NaN

这被称为数据透视或解除堆叠。关于此已经有很多问题在SO上了。 - Paul H
哦...好的,我在搜索将行转换为列时发现大多数问题仅涉及两列,而我有多列。不管怎样,在发布问题之前会再多阅读一些资料。 - yasin mohammed
1个回答

10
使用 set_indexunstack 相结合:
df = df.set_index(['PO ID','PO Name','Region', 'Date'])['Price'].unstack()
print (df)
Date                  07/2016  08/2016  09/2016
PO ID PO Name Region                           
1     AA      North     100.0    300.0    500.0
2     BB      South     200.0    400.0      NaN

如果需要聚合函数来处理重复数据,请使用pivot_tablegroupby
print (df)
   PO ID PO Name Region     Date  Price
0      1      AA  North  07/2016    100 <-for PO ID;PO Name;Region;Date different Price
1      1      AA  North  07/2016    500 <-for PO ID;PO Name;Region;Date different Price
2      2      BB  South  07/2016    200
3      1      AA  North  08/2016    300
4      2      BB  South  08/2016    400
5      1      AA  North  09/2016    500

df = df.pivot_table(index=['PO ID','PO Name','Region'], 
                    columns='Date', 
                    values='Price', 
                    aggfunc='mean')
print (df)
Date                  07/2016  08/2016  09/2016
PO ID PO Name Region                           
1     AA      North     300.0    300.0    500.0 <-(100+500)/2=300 for 07/2016
2     BB      South     200.0    400.0      NaN

df = df.groupby(['PO ID','PO Name','Region', 'Date'])['Price'].mean().unstack()
print (df)
Date                  07/2016  08/2016  09/2016
PO ID PO Name Region                           
1     AA      North     300.0    300.0    500.0 <-(100+500)/2=300 for 07/2016
2     BB      South     200.0    400.0      NaN

最后:

df = df.reset_index().rename_axis(None).rename_axis(None, axis=1)
print (df)
   PO ID PO Name Region  07/2016  08/2016  09/2016
0      1      AA  North    300.0    300.0    500.0
1      2      BB  South    200.0    400.0      NaN

我尝试了groupby的第三种解决方案,即在实际数据上使用set_index,因为该数据存在重复条目。 - yasin mohammed
有什么问题吗?如果有的话,你能详细解释一下吗? - jezrael
第三个解决方案完美地运行了。第一个解决方案出现了错误。ValueError: 索引包含重复条目,无法重塑。 - yasin mohammed
超棒,如果有重复的话,第三个解决方案是最快的。祝您愉快! - jezrael

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接