按条件分组的熊猫

时间:2021-04-23 04:46:22

标签: pandas

我有数据框

id           type             ip
1            mcma             123
1            mcms             124
1            mcda             125
1            mcds             126
2            cic              127
2            cmc              128

我想使用带有id的函数分组使用pandas并将类型应用于列表,如果id的类型为mcma,则ip是mcma的ip,其他是'-'

id           child                                                      ip
1            [{type: mcma, ip:123}, ..., {type:mcds, ip:126}]           123
2            [{type:cic, ip:127}, {type:cmc, ip:128}]                   -                       

目前,我只是获取 id 并输入正确,我不知道如何获取 ip 列。当前代码:

df = (df.groupby(["id"], as_index=True).apply(lambda x: x[["type", "ip"]].to_dict('record')).reset_index().rename(columns={0: 'child'}))

1 个答案:

答案 0 :(得分:1)

如果Series.where中的ipmcma不匹配,则替换NaN,然后聚合listip的第一个值:< /p>

df = (df.assign(ip = df['ip'].where(df['type'].eq('mcma')),
                type = df[['type','ip']].apply(lambda x: dict(x), axis=1))
        .groupby('id')
        .agg(child=('type',list), ip=('ip','first'))
        .reset_index())

df['ip'] = df['ip'].fillna('-')
print (df)
   id                                              child     ip
0   1  [{'type': 'mcma', 'ip': 123}, {'type': 'mcms',...    123
1   2  [{'type': 'cic', 'ip': 127}, {'type': 'cmc', '...      -