pandas -转置一列 [英] Pandas - transpose one column

查看:77
本文介绍了 pandas -转置一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我难以与大熊猫配合使用。



我有以下df:

 日期名称数量
2018年1月1日A 5
2018年1月1日B 6
2018年1月1日C 7
1 / 2/2018 A 9
1/2/2018 B 8
1/2/2018 C 6

我最终希望为每个日期的所有名称及其数量创建成对关联。为此,我尝试首先从此df创建以下输出:

  date ABC 
1 / 1/2018 5 6 7
1/2/2018 9 8 6

移调对我来说很难,因为我可以获得重复的列标题,但是我也不想通过先删除它们而丢失任何数据。我觉得答案可能与我不真正使用的panda实用程序有关,我可能正在转置上进行隧道传输。

解决方案

由于您未执行汇总,因此 pd.DataFrame.pivot 相对于 groupby / pivot_table code>:

  res = df.pivot(index ='date',column ='name',values = '数量')

打印(res)

名称ABC
日期
2018年1月1日5 6 7
1/2 / 2018 9 8 6

如果愿意,可以使用 reset_index 日期提升为一列。

I'm having difficulty using transpose with pandas.

I have the following 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

I eventually want to create a pairwise correlation for all the names and their quantities on each date. To to that end, I'm trying to create the following output from this df first:

 date       A    B    C
 1/1/2018   5    6    7
 1/2/2018   9    8    6

The transpose is difficult to me since I can get duplicate column headers, but I also don't want to lose any data by dropping them first. I have a feeling the answer may be with a panda utility that I don't really use and I may be tunneling on transpose...

解决方案

Since you aren't performing an aggregation, pd.DataFrame.pivot should be preferred to 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

If you wish you can use reset_index to elevate date to a column.

这篇关于 pandas -转置一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆