Python 将数据帧转换为dict并保留重复的索引
如果我们将数据帧转换为字典,重复条目(bob,20岁)将被删除。是否有任何可能的方法来生成一个字典,其值是字典列表?像这样的东西Python 将数据帧转换为dict并保留重复的索引,python,pandas,dictionary,dataframe,Python,Pandas,Dictionary,Dataframe,如果我们将数据帧转换为字典,重复条目(bob,20岁)将被删除。是否有任何可能的方法来生成一个字典,其值是字典列表?像这样的东西 vagrant@ubuntu-xenial:~/lb/f5/v12$ python Python 2.7.12 (default, Nov 12 2018, 14:36:49) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more informa
vagrant@ubuntu-xenial:~/lb/f5/v12$ python
Python 2.7.12 (default, Nov 12 2018, 14:36:49)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pandas as pd
>>> data = [{'name': 'bob', 'age': 20}, {'name': 'jim', 'age': 25}, {'name': 'bob', 'age': 30}]
>>> df = pd.DataFrame(data)
>>> df.set_index(keys='name', drop=False, inplace=True)
>>> df
age name
name
bob 20 bob
jim 25 jim
bob 30 bob
>>> df.to_dict(orient='index')
{'bob': {'age': 30, 'name': 'bob'}, 'jim': {'age': 25, 'name': 'jim'}}
>>>
如果您在索引上分组,应该可以这样做
groupby
详细信息groupby
允许我们根据唯一键对数据进行分区:
{k: g.to_dict(orient='records') for k, g in df.groupby(level=0)}
# {'bob': [{'age': 20, 'name': 'bob'}, {'age': 30, 'name': 'bob'}],
# 'jim': [{'age': 25, 'name': 'jim'}]}
对于每个组,使用“记录”方向将其转换为字典:
并且可以通过grouper键访问它
GroupBy。将
+应用于dict
apply
执行与字典理解相同的操作,它在每个组上迭代。唯一的区别是apply
需要最后一次来记录数据。可能的解决方案可以在这里找到:先生,您是一个向导和学者。非常感谢你!我为此挣扎了几个小时。我能得到这两种方法的分类吗?
{k: g.to_dict(orient='records') for k, g in df.groupby(level=0)}
# {'bob': [{'age': 20, 'name': 'bob'}, {'age': 30, 'name': 'bob'}],
# 'jim': [{'age': 25, 'name': 'jim'}]}
for k, g in df.groupby(level=0):
print(g, end='\n\n')
age name
name
bob 20 bob
bob 30 bob
age name
name
jim 25 jim
for k, g in df.groupby(level=0):
print(g.to_dict('r'))
[{'age': 20, 'name': 'bob'}, {'age': 30, 'name': 'bob'}]
[{'age': 25, 'name': 'jim'}]
df.groupby(level=0).apply(lambda x: x.to_dict('r')).to_dict()
# {'bob': [{'age': 20, 'name': 'bob'}, {'age': 30, 'name': 'bob'}],
# 'jim': [{'age': 25, 'name': 'jim'}]}