【问题标题】:Pandas: changing the row indices to column indices. Or Vice versaPandas:将行索引更改为列索引。或相反亦然
【发布时间】:2017-06-07 19:29:17
【问题描述】:
import pandas as pd
df = pd.DataFrame(data={'start':[1,2,3],'zone':['a','b','c']}); 
df['end']=[4,5,6]
df.set_index('zone',drop=True,inplace=True,append=False)
print(df)

      start  end
zone            
a         1    4
b         2    5
c         3    6

我想将此数据框修改为:

zone  a              b            c
      start  end     start  end   start  end
      1        4     2      5     3      6

通过将行索引更改为列索引。我需要这个,因为我想稍后融化数据框,所以它会变成一张长表。但我不知道如何将行索引与列索引一起融合。但是得到这个输出可以让我简单地使用:

pd.melt(df)

获取长桌。 如果有办法将列索引更改为行索引,我可以跳过将行索引更改为列索引的步骤,并立即获取长表。

请帮忙。

【问题讨论】:

    标签: python pandas indexing plot melt


    【解决方案1】:

    尝试使用stackto_frame 和 T 进行转置:

    df.stack().to_frame().T
    

    输出:

    zone     a         b         c    
         start end start end start end
    0        1   4     2   5     3   6
    

    【讨论】:

      【解决方案2】:

      从数组操作和多索引构造重构。

      pd.DataFrame(
          df.values.reshape(1, -1),
          columns=pd.MultiIndex.from_product([df.index, df.columns])
      )
      
            a         b         c    
        start end start end start end
      0     1   4     2   5     3   6
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-17
        • 2021-11-13
        • 1970-01-01
        • 1970-01-01
        • 2022-01-27
        • 2016-09-07
        • 2021-09-18
        • 2012-11-03
        相关资源
        最近更新 更多