我正在尝试重塑以下数据框:

            year    production     diversity
code_city
10701       2007    1096895.118        97
10701       2008    1485981.356       101
10701       2009    1592737.910       110
10702       2007    1196895.116        95
10702       2008    1285981.355       102
10702       2009    1392737.913       111
10703       2007    1496895.112        92
10703       2008    1585981.351       105
10703       2009    1692737.916       116


所需的输出是:

                         production    diversity

10701       2007-12-31  1096895.118        97
            2008-12-31  1485981.356       101
            2009-12-31  1592737.910       110
10702       2007-12-31  1196895.116        95
            2008-12-31  1285981.355       102
            2009-12-31  1392737.913       111
10703       2007-12-31  1496895.112        92
            2008-12-31  1585981.351       105
            2009-12-31  1692737.916       116


我一直在用这个:

table = pd.pivot_table(df_firms1, index=['code_city', 'year'], columns=['production', 'diversity'])


但我遇到很多错误。这是更好的方法吗?

最佳答案

第一个想法是使用reset_index

table = pd.pivot_table(df_firms1.reset_index(),
                       index=['code_city', 'year'],
                       columns=['production', 'diversity'])


但是通过示例数据可以获得:


  DataError:没有要聚合的数字类型


因此需要将year列转换为日期时间,然后将带有set_index参数的append=True转换为MultiIndex,将rename_axis的转换为索引名称:

df_firms1['year'] = pd.PeriodIndex(df_firms1['year'], freq='A').to_timestamp(how='e')

#alternative solution
#df_firms1['year'] = pd.to_datetime(df_firms1['year'], format='%Y') + pd.offsets.YearEnd()

df_firms1 = df_firms1.set_index('year', append=True).rename_axis([None, None])
print (df_firms1)

                   production  diversity
10701 2007-12-31  1096895.118         97
      2008-12-31  1485981.356        101
      2009-12-31  1592737.910        110
10702 2007-12-31  1196895.116         95
      2008-12-31  1285981.355        102
      2009-12-31  1392737.913        111
10703 2007-12-31  1496895.112         92
      2008-12-31  1585981.351        105
      2009-12-31  1692737.916        116

09-26 22:35
查看更多