1

我正在尝试从世界银行网站上整理一个数据集,我需要以某种方式重塑系列名称,以使系列名称成为第一行,并将年份全部排列在一个列中。数据集中有 50 年和 100 多个指标,所以这种重塑需要某种形式的自动化来为我工作。实际数据集的摘录如下图所示。

在此处输入图像描述

为了简化重塑过程,我还分享了一个可重现的代码,以显示我在列和行之间的排列方面所考虑的过渡,如迄今为止以叙述形式说明的那样。

请注意:可重现的代码并不是输出的完美表示,因为它非常简化,并且实际使用的数据集有数百个指标和数百个国家

import pandas as pd
data = {'Country':  ['Argentina', 'Argentina', 'Albania','Albania','Cuba','Cuba'],
        'Series': ['Indicator 1', 'Indicator 2', 'Indicator 1', 'Indicator 2','Indicator 1', 'Indicator 2', ],
        '2014': [1, 2, 3,4,5,6],
        '2015': [2, 4, 1,2,3,4]}
df = pd.DataFrame (data, columns = ['Country','Series','2014','2015'])
df

在此处输入图像描述

我想使用一个片段来达到这个结构,如代码下方的输出所示

import pandas as pd
data = {'Country':  ['Argentina', 'Argentina', 'Albania','Albania','Cuba','Cuba'],
        'Year': [2014,2015,2014,2015,2014,2015],
        'Indicator 1': [1, 2,3,1,5,3],
        'Indicator 2': [2,4,4,2,6,4]}
df = pd.DataFrame (data, columns = ['Country','Year','Indicator 1','Indicator 2'])
df

在此处输入图像描述

我正在寻找一个快速的代码片段来达到我的结果,而无需花费太多时间逐列解决方案。谢谢!

4

1 回答 1

1

DataFrame.set_index与 reshape byDataFrame.stack和一起使用Series.unstack

df1 = (df.set_index(['Country','Series'])
         .stack()
         .unstack(1)
         .rename_axis(columns=None, index=('Country','Year'))
         .reset_index())
print (df1)
     Country  Year  Indicator 1  Indicator 2
0    Albania  2014            3            4
1    Albania  2015            1            2
2  Argentina  2014            1            2
3  Argentina  2015            2            4
4       Cuba  2014            5            6
5       Cuba  2015            3            4

如果由于重复项使用DataFrame.meltwith DataFrame.pivot_table(可能的重复项由 聚合mean)而无法正常工作:

df1 = (df.melt(['Country','Series'], var_name='Year')
         .pivot_table(index=['Country','Year'], 
                      columns='Series', 
                      values='value',
                      aggfunc='mean')
         .rename_axis(columns=None, index=('Country','Year'))
         .reset_index()
         )
print (df1)
     Country  Year  Indicator 1  Indicator 2
0    Albania  2014            3            4
1    Albania  2015            1            2
2  Argentina  2014            1            2
3  Argentina  2015            2            4
4       Cuba  2014            5            6
5       Cuba  2015            3            4
于 2020-04-25T13:03:34.843 回答