本文介绍了逆透视 Pandas 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个 DataFrame 布局为:

I currently have a DataFrame laid out as:

        Jan Feb Mar Apr ...
2001    1   12  12  19
2002    9   ...
2003    ...

并且我想反透视"数据看起来像:

and I would like to "unpivot" the data to look like:

Date    Value
Jan 2001    1
Feb 2001    1
Mar 2001    12
...
Jan 2002    9

使用 pandas/NumPy 实现此目的的最佳方法是什么?

What is the best way to accomplish this using pandas/NumPy?

推荐答案

您只需要执行 df.unstack() 即可创建多索引系列,以月份为第一级,以年份为第一级作为二级指标.如果您希望它们成为列,那么只需在此之后调用 reset_index().

You just have to do df.unstack() and that will create a MultiIndexed Series with month as a first level and the year as the second level index. If you want them to be columns then just call reset_index() after that.

>>> df
      Jan  Feb
2001    3    4
2002    2    7
>>> df.unstack()
Jan  2001    3
     2002    2
Feb  2001    4
     2002    7
>>> df = df.unstack().reset_index(name='value')
>>> df
  level_0  level_1  value
0     Jan     2001      3
1     Jan     2002      2
2     Feb     2001      4
3     Feb     2002      7
>>> df.rename(columns={'level_0': 'month', 'level_1': 'year'}, inplace=True)
>>> df
  month  year  value
0   Jan  2001      3
1   Jan  2002      2
2   Feb  2001      4
3   Feb  2002      7

这篇关于逆透视 Pandas 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 14:37