Flatten Pandas DataFrame 添加后缀
Flatten Pandas DataFrame adding a suffix
我有以下 Pandas DataFrame:
POS Price Cost (...)
10122 100 20
10123 500 5
(...)
我想旋转行和列,获得单行,添加后缀为:
Price_POS10122 Cost_POS10122 Price_POS10123 Cost_POS10123 (...)
100 20 500 5
(...)
我怎样才能做到这一点?
让我们拆开:
df=df.set_index('POS').unstack().to_frame().T
df.columns=[f"{x}_POS{y}" for x,y in df.columns]
df 的输出:
Price_POS10122 Price_POS10123 Cost_POS10122 Cost_POS10123
0 100 500 20 5
我有以下 Pandas DataFrame:
POS Price Cost (...)
10122 100 20
10123 500 5
(...)
我想旋转行和列,获得单行,添加后缀为:
Price_POS10122 Cost_POS10122 Price_POS10123 Cost_POS10123 (...)
100 20 500 5
(...)
我怎样才能做到这一点?
让我们拆开:
df=df.set_index('POS').unstack().to_frame().T
df.columns=[f"{x}_POS{y}" for x,y in df.columns]
df 的输出:
Price_POS10122 Price_POS10123 Cost_POS10122 Cost_POS10123
0 100 500 20 5