pandas 将行转置为列- Python

bmvo0sr5  于 2023-01-19  发布在  Python
关注(0)|答案(1)|浏览(97)

https://docs.google.com/spreadsheets/d/1ew9_hV30N46zlWKW9Pi-nLM5XxOUUGDbVMRa3FJzEoI/edit#gid=1420260456
请指导我的过程,如果我们可以使用一些Pandas功能,如融化/堆叠转换成该格式。
我已经审查了一些功能,如使用Pandas融化功能,但是,我无法破解相同的正确代码。

xdnvmnnf

xdnvmnnf1#

下面是使用您提到的一些panda reshaping * 函数 * 和pivot_table的命题:

out = (
        pd.read_excel("/tmp/Untitled spreadsheet.xlsx", sheet_name="Input")
             .pipe(lambda df: df.assign(**{col: df[col].ffill() for col in ["Product", "Tier Type"]}))
             .rename(columns={"Tier Type": "tier_type", "Unnamed: 2": "Type"})
             .melt(id_vars=['Product','tier_type','Type'], value_vars=['Unnamed: 3','Unnamed: 4'], value_name='Value')
             .pivot_table(index=['Product','tier_type'], columns='Type', values='Value', aggfunc=lambda x: x)
             .explode(["Cost", "Velocity"])
             .reset_index()
             .rename_axis(None, axis=1)
      )

输出:

print(out)
   Product tier_type Cost Velocity
0        A     Retro   10    0-600
1        A     Retro   20     601+
2        B     Retro   30   0-1000
3        B     Retro   40    1000+
4        C     Retro   50     0-10
..     ...       ...  ...      ...
13       G     Retro  NaN      NaN
14       H     Retro  NaN      NaN
15       H     Retro  NaN      NaN
16       I     Retro  NaN      NaN
17       I     Retro  NaN      NaN

[18 rows x 4 columns]

相关问题