我有数据
id type ip
1 mcma 123
1 mcms 124
1 mcda 125
1 mcds 126
2 cic 127
2 cmc 128我想用id按功能分组使用熊猫数据,并应用类型列表,ip是mcma的ip如果id有mcma类型,其他是'-‘。
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'}))发布于 2021-04-23 04:49:33
如果ip与Series.where中的NaN不匹配,则替换list,然后聚合list和ip的第一个值。
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', '... -https://stackoverflow.com/questions/67224139
复制相似问题