我有一个pandas.DataFrame不会像我期望的那样旋转。虽然pivot_table
正确安排了所有内容,但它使用聚合函数来实现这一事实令人反感。此外,pivot_table
似乎返回了一个不必要的复杂对象,而不是一个平面数据框。
考虑以下示例
import pandas as pd
df = pd.DataFrame({'firstname':['Jon']*3+['Amy']*2,
'lastname':['Cho']*3+['Frond']*2,
'vehicle':['bike', 'car', 'plane','bike','plane'],
'weight':[81.003]*3+[65.6886]*2,
'speed':[29.022, 95.1144, 302.952, 27.101, 344.2],})
df.set_index(['firstname','lastname','weight'])
print('------ Unnecessary pivot_table does averaging ------')
print(pd.pivot_table(df, values='speed',
rows='firstname','lastname','weight'],
cols='vehicle'))
print('------ pivot method dies ------')
print(df.pivot( index=['firstname','lastname','weight'],
columns='vehicle',
values='speed'))
结果pivot_table
是
vehicle bike car plane
firstname lastname weight
Amy Frond 65.6886 27.101 NaN 344.200
Jon Cho 81.0030 29.022 95.1144 302.952
有没有办法pivot
提供与命令基本相同的输出pivot_table
(但希望更平坦、更整洁)?如果做不到这一点,我如何使输出变平pivot_table
?我想要的输出更像是这样的:
firstname lastname weight bike car plane
Amy Frond 65.6886 27.101 NaN 344.200
Jon Cho 81.0030 29.022 95.1144 302.952