Skip to main content
 首页 » 编程设计

python之reshape 我的 Pandas 数据框

2024年10月01日8cyq1162

我有以下数据框:

   name     Jan     Feb     Mar     Apr     May     Jun     Jul     Aug  \ 
0     IBM  156.08  160.01  159.81  165.22  172.25  167.15  164.75  152.77    
1    MSFT   45.51   43.08   42.13   43.47   47.53   45.96   45.61   45.51    
2  GOOGLE  512.42  537.99  559.72  540.50  535.24  532.92  590.09  636.84    
3   APPLE  110.64  125.43  125.97  127.29  128.76  127.81  125.34  113.39    
 
      Sep     Oct     Nov     Dec   
0  145.36  146.11  137.21  137.96   
1   43.56   48.70   53.88   55.40   
2  617.93  663.59  735.39  755.35   
3  112.80  113.36  118.16  111.73   

我想将其转换为以下内容:

 Month        AAPL        GOOG         IBM 
0   Jan  117.160004  534.522445  153.309998 
1   Feb  128.460007  558.402511  161.940002 
2   Mar  124.430000  548.002468  160.500000 
3   Apr  125.150002  537.340027  171.289993 
4   May  130.279999  532.109985  169.649994 

我一直在摆弄 melt 和 pivot,但不知道如何让它发挥作用。 任何建议将不胜感激。

谢谢

请您参考如下方法:

让我们使用“set_index”、“rename_axis”和 T 进行转置。

df.set_index('name')\ 
  .rename_axis(None).T\ 
  .rename_axis('Month')\ 
  .reset_index() 

输出:

  Month     IBM   MSFT  GOOGLE   APPLE 
0   Jan  156.08  45.51  512.42  110.64 
1   Feb  160.01  43.08  537.99  125.43 
2   Mar  159.81  42.13  559.72  125.97 
3   Apr  165.22  43.47  540.50  127.29 
4   May  172.25  47.53  535.24  128.76 
5   Jun  167.15  45.96  532.92  127.81 
6   Jul  164.75  45.61  590.09  125.34 
7   Aug  152.77  45.51  636.84  113.39