繁体   English   中英

将行转为列 - Python

[英]Transposing the rows to columns- Python

https://docs.google.com/spreadsheets/d/1ew9_hV30N46zlWKW9Pi-nLM5XxOUUGDbVMRa3FJzEoI/edit#gid=1420260456

如果我们可以使用一些 pandas 功能(如 melt/stack)转换成那种格式,请指导我这个过程。

我已经回顾过有一些功能,比如使用 Pandas melt function,但是,我无法破解相同的正确代码。

这是一个使用您提到的一些 pandas重塑函数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)
      )

Output:

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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM