如何将pandas Dataframe列名设置为标题?

时间:2016-08-07 10:30:32

标签: python pandas

我使用以下代码创建了一个Dataframe。

>>>in:    df_final = pandas.DataFrame(combined_data, columns=['Item', aa, bb, cc, dd])

>>>out:
                         Item     FY2012     FY2013     FY2014    FY2015
0               Total Revenue    654.766     535.79    321.394   445.241   
1                Gross Profit    256.776    268.412     156.47   220.687   
2                  Net Income     60.994     44.026     57.469    41.273   
3                      EBITDA    111.324    110.268   (41.478)    83.382

但是,当我尝试通过添加.T来转置代码时,我得到:

>>>in:    df_final = pandas.DataFrame(combined_data, columns=['Item', aa, bb, cc, dd]).T

>>>>out:    
                       0             1           2         3
Item            Total Revenue  Gross Profit  Net Income    EBITDA   
FY2012                654.766       256.776      60.994   111.324   
FY2013                 535.79       268.412      44.026   110.268   
FY2014                321.394        156.47      57.469  (41.478)   
FY2015                445.241       220.687      41.273    83.382   

Transposing之后,我应该怎么做,而不是将[0, 1, 2, 3]作为标题,而是将Total Revenue Gross Profit Net Income EBITDA作为标题呢?

IE:如果我没有Transpose数据帧,print(df.columns.values)会给我Item FY2012 FY2013 FY2014 FY2015作为标题。但在Transposing数据框后,[0, 1, 2, 3]成为标题,而不是Total Revenue Gross Profit Net Income EBITDA

1 个答案:

答案 0 :(得分:2)

您需要将Item列设置为index,以便在转置它时成为'columns':

df.set_index('Item').T
Out: 
Item    Total Revenue  Gross Profit  Net Income   EBITDA
FY2012        654.766       256.776      60.994  111.324
FY2013        535.790       268.412      44.026  110.268
FY2014        321.394       156.470      57.469  -41.478
FY2015        445.241       220.687      41.273   83.382