我在对 pandas 使用转置时遇到困难。
我有以下 df:
date name quantity
1/1/2018 A 5
1/1/2018 B 6
1/1/2018 C 7
1/2/2018 A 9
1/2/2018 B 8
1/2/2018 C 6
我最终想为每个日期的所有名称及其数量创建成对关联。为此,我试图首先从这个 df 创建以下输出:
date A B C
1/1/2018 5 6 7
1/2/2018 9 8 6
转置对我来说很难,因为我可以获得重复的列标题,但我也不想通过先删除它们来丢失任何数据。我觉得答案可能是我并没有真正使用的 Pandas 实用程序,我可能正在转置隧道...
最佳答案
由于您没有执行聚合,pd.DataFrame.pivot
应该优先于 groupby
/pivot_table
:
res = df.pivot(index='date', columns='name', values='quantity')
print(res)
name A B C
date
1/1/2018 5 6 7
1/2/2018 9 8 6
如果您愿意,可以使用 reset_index
将 date
提升为一列。
关于python - Pandas - 转置一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52541982/