对于每一行,我希望将行的索引更改为 column_index,并将整个内容从 x 行 * y 列拆分为 1 行 * x*y 列形状。
import pandas as pd
df = pd.DataFrame(data=[['Jon', 21, 1.77,160],['Jane',44,1.6,130]],columns=['name','age', 'height','weight'])
want = pd.DataFrame(data=[['Jon', 21, 1.77,160,'Jane',44,1.6,130]],columns=['name_0','age_0', 'height_0','weight_0','name_1','age_1', 'height_1','weight_1'])
# original df
name age height weight
0 Jon 21 1.77 160
1 Jane 44 1.60 130
# desired df - want
name_0 age_0 height_0 weight_0 name_1 age_1 height_1 weight_1
0 Jon 21 1.77 160 Jane 44 1.6 130
我尝试了df.unstack().to_frame().T
,虽然它将行数减少到一,但它创建了一个多重索引,所以并不理想:
name age height weight
0 1 0 1 0 1 0 1
0 Jon Jane 21 44 1.77 1.6 160 130
我认为数据透视表在这里不起作用。
最佳答案
使用stack
并展平 MultiIndex:
out = df.stack().swaplevel().to_frame().T
out.columns = out.columns.map(lambda x: f'{x[0]}_{x[1]}')
输出:
name_0 age_0 height_0 weight_0 name_1 age_1 height_1 weight_1
0 Jon 21 1.77 160 Jane 44 1.6 130
关于python - 重新格式化/旋转 pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75827088/