pandas :创建一个以元组为键的字典 [英] Pandas: create a dictionary with a tuple as key
本文介绍了 pandas :创建一个以元组为键的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出此DataFrame
:
import pandas as pd
first=[0,1,2,3,4]
second=[10.2,5.7,7.4,17.1,86.11]
third=['a','b','c','d','e']
fourth=['z','zz','zzz','zzzz','zzzzz']
df=pd.DataFrame({'first':first,'second':second,'third':third,'fourth':fourth})
df=df[['first','second','third','fourth']]
first second third fourth
0 0 10.20 a z
1 1 5.70 b zz
2 2 7.40 c zzz
3 3 17.10 d zzzz
4 4 86.11 e zzzzz
我可以创建一个以列列表作为值的字典,像这样:
I can create a dictionary with a list of columns as values, like this:
d = {df.loc[idx, 'first']: [df.loc[idx, 'second'], df.loc[idx, 'third']] for idx in range(df.shape[0])}
但是如何创建一个包含以first
和second
作为键的元组的字典?
but how can I create a dictionary with, say, a tuple containing first
and second
as key?
结果将是:
In[1]:d
Out[1]:
{(0,10.199999999999999): 'a',
(1,5.7000000000000002): 'b',
(2,7.4000000000000004): 'c',
(3,17.100000000000001): 'd',
(4,86.109999999999999): 'e'}
PS:如何确定pandas
不会弄乱值? 10.20现在变成了10.1999999999 ...
PS: and how could I make sure that pandas
doesn't mess up with the values? 10.20 has now become 10.1999999999...
推荐答案
您需要通过set_index
,然后调用
You need create MultiIndex
by set_index
and then call Series.to_dict
:
a = df.set_index(['first','second']).third.to_dict()
print (a)
{(2, 7.4): 'c', (1, 5.7): 'b', (3, 17.1): 'd', (0, 10.2): 'a', (4, 86.11): 'e'}
这篇关于 pandas :创建一个以元组为键的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文