我正在运行Python 3.6和Pandas 0.19.2,并且有一个DataFrame,如下所示:
Name Chain Food Healthy
George McDonalds burger False
George KFC chicken False
John Wendys burger False
John McDonalds salad True
我想将此数据帧转换为dict,如下所示:
health_data = {'George': {'McDonalds': {'Food': 'burger', 'Healthy':False},
'KFC': {'Food': 'chicken', 'Healthy':False}},
'John': {'Wendys': {'Food': 'burger', 'Healthy':False},
'McDonalds': {'Food': 'salad', 'Healthy': True}}}
到目前为止,我的想法是:
df.groupby
对名称列进行分组df.to_dict()
将数据框转换为字典,如下所示:
health_data = input_data.set_index('Chain').T.to_dict()
思考?在前面感谢您的帮助。
答案 0 :(得分:5)
字典理解+ groupby
{n: grp.loc[n].to_dict('index')
for n, grp in df.set_index(['Name', 'Chain']).groupby(level='Name')}
{'George': {'KFC': {'Food': 'chicken', 'Healthy': False},
'McDonalds': {'Food': 'burger', 'Healthy': False}},
'John': {'McDonalds': {'Food': 'salad', 'Healthy': True},
'Wendys': {'Food': 'burger', 'Healthy': False}}}
<强> defaultdict
强>
from collections import defaultdict
d = defaultdict(dict)
for i, row in df.iterrows():
d[row.Name][row.Chain] = row.drop(['Name', 'Chain']).to_dict()
dict(d)
{'George': {'KFC': {'Food': 'chicken', 'Healthy': False},
'McDonalds': {'Food': 'burger', 'Healthy': False}},
'John': {'McDonalds': {'Food': 'salad', 'Healthy': True},
'Wendys': {'Food': 'burger', 'Healthy': False}}}
答案 1 :(得分:4)
我认为你很亲密。
df = df.groupby('Name')[['Chain','Food','Healthy']]
.apply(lambda x: x.set_index('Chain').to_dict(orient='index'))
.to_dict()
print (df)
{'George': {'KFC': {'Healthy': False, 'Food': 'chicken'},
'McDonalds': {'Healthy': False, 'Food': 'burger'}},
'John': {'McDonalds': {'Healthy': True, 'Food': 'salad'},
'Wendys': {'Healthy': False, 'Food': 'burger'}}}