Pandas 将列名转换为第一行

Pandas 将列名转换为第一行,pandas,Pandas,我想将以下数据帧转换为json df: A sector B sector C sector TTM Ratio                 --   35.99   12.70  20.63  14.75      23.06 RRM Sales            --  114.57    1.51  

我想将以下数据帧转换为json

df:
                               A   sector    B     sector    C     sector                              
TTM Ratio                      --   35.99   12.70  20.63  14.75      23.06
RRM Sales                      --  114.57    1.51   5.02   1.00    4594.13
MQR book                     1.48    2.64    1.02   2.46   2.73       2.74
TTR cash                       --   14.33    7.41  15.35   8.59  513854.86
为了使用函数
df.to_json()
实现这一点,我需要在列和索引中有唯一的名称

因此,我要寻找的是将列名转换成一行并具有默认的列号。简而言之,我希望得到以下输出:

df:
                               0     1       2       3       4       5 
                               A   sector    B     sector    C     sector                              
TTM Ratio                      --   35.99   12.70  20.63  14.75      23.06
RRM Sales                      --  114.57    1.51   5.02   1.00    4594.13
MQR book                     1.48    2.64    1.02   2.46   2.73       2.74
TTR cash                       --   14.33    7.41  15.35   8.59  513854.86

将列名转换为第一行,以便正确进行转换

使用
范围的
列表
和原始列名的赋值方式:

print (range(len(df.columns)))
range(0, 6)

#for python2 list can be omit
df.columns = [list(range(len(df.columns))), df.columns]
或:


也可以使用
范围索引

print (pd.RangeIndex(len(df.columns)))
RangeIndex(start=0, stop=6, step=1)

df.columns = pd.MultiIndex.from_arrays([pd.RangeIndex(len(df.columns)), df.columns])
print (df)
              0       1      2        3      4          5
              A  sector      B   sector      C     sector
TTM Ratio    --   35.99  12.70    20.63  14.75      23.06
RRM Sales    --  114.57   1.51     5.02   1.00    4594.13
MQR book   1.48    2.64   1.02     2.46   2.73       2.74
TTR cash     --   14.33   7.41    15.35   8.59  513854.86

您也可以在numpy中使用vstack:

>>> df
   x  y  z
0  8  7  6
1  6  5  4

>>> pd.DataFrame(np.vstack([df.columns, df]))
   0  1  2
0  x  y  z
1  8  7  6
2  6  5  4
在这种情况下,列将成为实际的第一行

>>> df
   x  y  z
0  8  7  6
1  6  5  4

>>> pd.DataFrame(np.vstack([df.columns, df]))
   0  1  2
0  x  y  z
1  8  7  6
2  6  5  4