从单个列创建多个列并按 pandas 进行分组

问题描述 投票:0回答:2
work = pd.DataFrame({"JOB" : ['JOB01', 'JOB01', 'JOB02', 'JOB02', 'JOB03', 'JOB03'],
"STATUS" : ['ON_ORDER', 'ACTIVE','TO_BE_ALLOCATED', 'ON_ORDER', 'ACTIVE','TO_BE_ALLOCATED'],
"PART" : ['PART01', 'PART02','PART03','PART04','PART05','PART06']})

如何使用 Pandas 按作业进行分组,根据值将状态拆分为列,并根据作业连接部分字段。

所需输出:

JOB    | ON_ORDER  | ACTIVE   | TO_BE_ALLOCATED | PART_CON
JOB01  | True      | True     | False           | Part01\nPart02
JOB02  | True      | False    | True            | Part03\nPart04
JOB03  | False     | True     | True            | Part05\nPart06
python pandas dataframe group-by
2个回答
4
投票

尝试:

x = df.groupby("JOB")["PART"].agg(", ".join).rename("PART_CON")
y = pd.crosstab(df["JOB"], df["STATUS"]).astype(bool)
print(pd.concat([y, x], axis=1).reset_index())

打印:

     JOB  ACTIVE  ON_ORDER  TO_BE_ALLOCATED        PART_CON
0  JOB01    True      True            False  PART01, PART02
1  JOB02   False      True             True  PART03, PART04
2  JOB03    True     False             True  PART05, PART06

0
投票

另一种可能的解决方案,使用

pivot_table

out = work.pivot_table(
    index='JOB', columns='STATUS', values='PART', aggfunc='first')
out.notna().assign(
    PART_CON = out.apply(
        lambda x: '\n'.join(x.sort_values().dropna()), axis=1))
© www.soinside.com 2019 - 2024. All rights reserved.