使用带有非唯一列"index"选项将 pandas 数据帧转换为字典



我有一个熊猫数据帧,df1,有300万条这样的记录。

name,address,zipcode james,abd sdfse sdfex sdfs,234212 james,aseesdfwerw asdfasee,234355 mathew,asfasee sdfadf,43453

我想将其转换为字典,以name作为索引。

这是我所做的:

df1.set_index('name',in_place=True) dict1=df1.to_dict('index')

由于name不是一个唯一的列,我可以看到一些记录在转换为字典后被删除。谁能帮我如何使其成为列表字典/其他处理方式?

一种可能的解决方案是创建list s:

d = df.groupby('name').agg(lambda x: x.tolist()).to_dict('index')
print (d)
{'james': {'address': ['abd sdfse sdfex sdfs', 'aseesdfwerw asdfasee'], 
             'zipcode': [234212, 234355]}, 
 'mathew': {'address': ['asfasee sdfadf'], 
            'zipcode': [43453]}}

相关内容

最新更新