但是,当我使用提供的解决方案时,我之前曾问过类似的问题 - pandas - Reorganize a multi-row & multi-column DataFrame into single-row & multi-column DataFrame:
v = df.unstack().to_frame().sort_index(level=1).T
v.columns = v.columns.map('_'.join)
关于以下DataFrame(切换列和行值与上述答案中的示例相比),
index A B C
1 Apple Orange Grape
2 Car Truck Plane
3 House Apartment Garage
但是,此行:v.columns = v.columns.map('_'.join)
会引发以下错误:TypeError: sequence item 1: expected str instance, int found
有没有办法获得以下输出?
A_1 A_2 A_3 B_1 B_2 B_3 C_1 C_2 C_3
0 Apple Orange Grape Car Truck Plane House Apartment Garage
谢谢。
答案 0 :(得分:1)
当标题是整数时发生。请尝试使用.format
:
v = df.unstack().to_frame().T
v.columns = v.columns.map('{0[0]}_{0[1]}'.format)
print(v)
A_1 A_2 A_3 B_1 B_2 B_3 C_1 C_2 C_3
0 Apple Car House Orange Truck Apartment Grape Plane Garage