如何获得此效果?
输入数据:
val1 val2 val3 val4
0 A1.1 A2.1 A3.1 A4.1
1 A1.2 A2.2 A3.2 A4.2
2 A1.3 A2.3 A3.3 A4.3
输出数据:
new_column A1.1 A1.2 A1.3
0 val2 A2.1 A2.2 A2.3
1 val3 A3.1 A3.2 A3.3
2 val4 A4.1 A4.2 A4.3
A1.1,A1.2,A1.3是列名。 我尝试了枢轴,非透视,拆散,但我无法达到预期的效果。
答案 0 :(得分:2)
使用set_index
+ T
+ rename_axis
+ reset_index
:
df = df.set_index('val1').T.rename_axis('new_col').reset_index().rename_axis(None,1)
print (df)
new_col A1.1 A1.2 A1.3
0 val2 A2.1 A2.2 A2.3
1 val3 A3.1 A3.2 A3.3
2 val4 A4.1 A4.2 A4.3
答案 1 :(得分:1)
set_index
+ rename_axis
df.set_index('val1').T.rename_axis(None,1)
Out[499]:
A1.1 A1.2 A1.3
val2 A2.1 A2.2 A2.3
val3 A3.1 A3.2 A3.3
val4 A4.1 A4.2 A4.3
df.set_index('val1').T.rename_axis(None,1).reset_index().rename(columns={'index':'new_col'})
Out[524]:
new_col A1.1 A1.2 A1.3
0 val2 A2.1 A2.2 A2.3
1 val3 A3.1 A3.2 A3.3
2 val4 A4.1 A4.2 A4.3