将pandas DF转换为特殊词典?

流沙

我有一个他们购买的带有customer_id,date,product_id的DataFrame。我想将此DataFrame转换为2字典

customer_id    date     product_id
1            10/3/2017  1234
2            11/3/2017  4321
1            10/3/2017  7384
2            10/3/2017  1234

我想要这样的输出:

{'10/3/2017': {1 : 1234, 1: 7384, 2: 1234}, '11/3/2017': {2 : 4321}}

我尝试使用

df.set_index(['date','customer_number']).T.to_dict('record')

但这不会给我2本字典。

{('10/3/2017', 1): 1234', .....}
耶斯列尔

第一行和第三行中的每组重复项存在问题,因此返回1: 7384groupby与lambda函数一起使用的解决方案用于转换为dict每个组,然后to_dict转换为final Series

d = df.groupby('date').apply(lambda x: dict(zip(x['customer_id'], x['product_id']))).to_dict()
print (d)
{'10/3/2017': {1: 7384, 2: 1234}, '11/3/2017': {2: 4321}}

编辑:

s = df.groupby(['date','customer_id'])['product_id'].apply(list)
d = {k: v[k].to_dict() for k, v in s.groupby(level=0)}
print (d)
{'10/3/2017': {1: [1234, 7384], 2: [1234]}, '11/3/2017': {2: [4321]}}

如果不需要一个项目列表:

s = (df.groupby(['date','customer_id'])['product_id']
       .apply(lambda x: list(x) if len(x) > 1 else x.iat[0]))
d = {k: v[k].to_dict() for k, v in s.groupby(level=0)}
print (d)
{'10/3/2017': {1: [1234, 7384], 2: 1234}, '11/3/2017': {2: 4321}}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章