我正在使用python中的代码,我想转换这个dataFrame:
在:
进入此DataFrame:
我尝试使用以下命令来旋转表:
pd.pivot_table(mytable, index = [JAN, FEB, MAR])
但我对结果不满意......
答案 0 :(得分:2)
这应该有效:
df = pd.melt(df, id_vars=['Word'], value_vars=['JAN', 'FEB', 'MAR']).dropna()
df = df.pivot(index='variable', columns='value', values='Word')
答案 1 :(得分:0)
创建原始数据:
df = pd.DataFrame({'Word':['Hello','Python','Pikachu','Phone'],'JAN':['3','1','2',np.nan],'FEB':['3','1',np.nan,'2'],'MAR':[np.nan,'2','1','3']},columns=['Word','JAN','FEB','MAR'])
df
输入数据帧:
Word JAN FEB MAR
0 Hello 3 3 NaN
1 Python 1 1 2
2 Pikachu 2 NaN 1
3 Phone NaN 2 3
使用set_index
,stack
,unstack
重塑数据:
df1 = df.set_index('Word').stack().reset_index().set_index(['level_1',0]).unstack().rename_axis(None)
df1.columns = df1.columns.droplevel(None)
df1
输出:
1 2 3
FEB Python Phone Hello
JAN Python Pikachu Hello
MAR Pikachu Python Phone