在pivot_表之后将索引重置为平坦

2024-05-15 21:29:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据帧df

           Datum    HH  DayPrecipitation
9377    2016-01-26  18  3
9378    2016-01-26  19  4
9379    2016-01-26  20  11
9380    2016-01-26  21  23
9381    2016-01-26  22  12

我使用

df.pivot_table(index = 'Datum', columns='HH' ,values = 'DayPrecipitation')

这给我留下了一个双栏

     HH     18  19  20  21  22
  Datum                 
2016-01-26  3   4   11  23  12

我想使列看起来像这样,并重命名列:

   Datum  col1 col2  col3 col4 col5 col6            
2016-01-26  1    3    4    11   23   12

但是,当我使用reset_index时,它只添加了另一个索引列,而没有删除multi_索引。 有人知道如何实现上述表格吗?非常感谢您的帮助


Tags: columns数据dfindexhhtable命名col2
2条回答

您可以删除['DayPrecipitation']中的[]以避免MultiIndex in columns,然后通过^{}设置新列名,并通过^{}将索引最后转换为列:

L = [f'col{x+1}' for x in range(df['HH'].nunique())]
df1 = (df.pivot_table(index = 'Datum', columns='HH' ,values = 'DayPrecipitation')
         .rename_axis(None,axis=1)
         .set_axis(L, inplace=False, axis=1)
         .reset_index())
print (df1)
        Datum  col1  col2  col3  col4  col5
0  2016-01-26     3     4    11    23    12

试用

df.T.reset_index(drop=True).T

相关问题 更多 >