如何在Python中进行行列转换/透视?

时间:2019-11-09 17:51:32

标签: python pandas

我已经用Python编写了以下代码

import pandas as pd


data = {'Mnth':["Jan", "Feb", "Mar", "April","May"],         
       'Income':["80","90","60", "30", "50"]} 

df = pd.DataFrame(data) 

print(df)

结果为

enter image description here

我正在寻找这样的转变

Jan    Feb  Mar  April   May
---    ---  ---  -----   ---- 

80     90   60     30    50

我尝试过使用Pivot功能,

pivot  =df.pivot(index ='Mnth', columns ='Income') 

print(pivot)

但结果是

Empty DataFrame
Columns: []
Index: [April, Feb, Jan, Mar, May]

1 个答案:

答案 0 :(得分:1)

方法1:DataFrame.set_index + DataFrame.transpose

new_df=df.set_index('Mnth').T
print(new_df)

输出

Mnth   Jan Feb Mar April May
Income  80  90  60    30  50

您可以使用DataFrame.rename_axis删除列名(Mnth,然后使用DataFrame.reset_index重置DataFrame索引

new_df=df.set_index('Mnth').T.rename_axis(columns=None).reset_index(drop=True)
print(new_df)

输出

  Jan Feb Mar April May
0  80  90  60    30  50

方法2:DataFrame.pivot_table

df['Income']=df['Income'].astype(int)
new_df=df.pivot_table(columns='Mnth',values='Income')
print(new_df)

输出

Mnth    April  Feb  Jan  Mar  May
Income     30   90   80   60   50

数据透视表,其str类型为:

有必要更改要添加的默认aggfunc:

new_df=df.pivot_table(columns='Mnth',values='Income',aggfunc=lambda x: ' '.join(x))
print(new_df)

Mnth   April Feb Jan Mar May
Income    30  90  80  60  50