gpt4 book ai didi

python - Pandas 通过条件检查 reshape 从长到宽的多列数据框

转载 作者:太空宇宙 更新时间:2023-11-04 11:13:00 25 4
gpt4 key购买 nike

我有一个 pandas 数据框,如下所示:

id     group    type    action    cost
101 A 1 10
101 A 1 repair 3
102 B 1 5
102 B 1 repair 7
102 B 1 grease 2
102 B 1 inflate 1
103 A 2 12
104 B 2 9

我需要将它从长改成宽,但取决于 action 列的值,如下所示:

id     group    type    action_std    action_extra
101 A 1 10 3
102 B 1 5 10
103 A 2 12 0
104 B 2 9 0

换句话说,对于 action 字段为空的行,cost 值应该放在 action_std 列下,而对于行对于非空的 action 字段,cost 值应汇总在 action_extra 列下。

我尝试了 groupby/agg/pivot 的几种组合,但我找不到任何完全有效的解决方案...

最佳答案

我建议您简单地将 cost 列拆分为 costcost_extra 列。类似于以下内容:

import numpy as np

result = df.assign(
cost_extra=lambda df: np.where(
df['action'].notnull(), df['cost'], np.nan
)
).assign(
cost=lambda df: np.where(
df['action'].isnull(), df['cost'], np.nan
)
).groupby(
["id", "group", "type"]
)["cost", "cost_extra"].agg(
"sum"
)

结果 看起来像:

                cost  cost_extra
id group type
101 A 1 10.0 3.0
102 B 1 5.0 10.0
103 A 2 12.0 0.0
104 B 2 9.0 0.0

关于python - Pandas 通过条件检查 reshape 从长到宽的多列数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57742001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com