Python 从数据帧创建dict的dict
我正在尝试将数据帧转换为以下格式的dict:Python 从数据帧创建dict的dict,python,pandas,dictionary,Python,Pandas,Dictionary,我正在尝试将数据帧转换为以下格式的dict: df name age country state pincode 0 user1 10.0 in tn 1.0 1 user2 11.0 us tx 2.0 2 user3 12.0 eu fr 3.0 我目前正在通过以下声明来实现这一点: op = {} for i, row in df.iterrows(): op[row['nam
df
name age country state pincode
0 user1 10.0 in tn 1.0
1 user2 11.0 us tx 2.0
2 user3 12.0 eu fr 3.0
我目前正在通过以下声明来实现这一点:
op = {}
for i, row in df.iterrows():
op[row['name']] = {'age':row['age'],'country':row['country'],'state':row['state'],'pincode':row['pincode']}
如果df中添加了其他列,我希望解决方案能够正常工作。例如电话号码。因为我写的语句是静态的,所以它不会在输出中给我额外的行。
pandas中是否有内置的方法可以执行此操作?您想先将
名称设置为索引:
df.set_index('name').to_dict('index')
输出:
{'user1': {'age': 10.0, 'country': 'in', 'state': 'tn', 'pincode': 1.0},
'user2': {'age': 11.0, 'country': 'us', 'state': 'tx', 'pincode': 2.0},
'user3': {'age': 12.0, 'country': 'eu', 'state': 'fr', 'pincode': 3.0}}
与orient='index'
一起使用:
d = df.set_index('name').to_dict(orient='index')
print (d)
{'user1': {'age': 10.0, 'country': 'in', 'state': 'tn', 'pincode': 1.0},
'user2': {'age': 11.0, 'country': 'us', 'state': 'tx', 'pincode': 2.0},
'user3': {'age': 12.0, 'country': 'eu', 'state': 'fr', 'pincode': 3.0}}
如有可能,应省略的其他列可以在选择之前进行裁剪或选择:
d = df.set_index('name')[['age','country','state','pincode']].to_dict(orient='index')
这可能不太易读,但这里有一行字典理解:
{k:{a:b for a,b in zip(df.columns.tolist()[1:], v)}
for k,v in zip(df['name'].to_list(), df.iloc[:,1:].to_numpy().tolist())}
还有一个问题。假设有几个列没有值。是否有快捷方式删除它们?现在,它们的值为'nan',这起作用-{k1:{k:v代表k,v在v1.items()中,如果pd.notnull(v)}代表k1,v1在d.items()中。但还有其他现成的解决方案吗?@rakesh不幸没有。还有一个问题。假设有几列没有值。是否有快捷方式删除它们?现在它们的值为'nan',例如:{'age':10.0,'country':'in','state':'tn','pincode':1.0,'ph':nan},我希望删除键ph
{k:{a:b for a,b in zip(df.columns.tolist()[1:], v)}
for k,v in zip(df['name'].to_list(), df.iloc[:,1:].to_numpy().tolist())}