gpt4 book ai didi

python - Pandas:创建一个以元组为键的字典

转载 作者:行者123 更新时间:2023-12-02 00:48:02 26 4
gpt4 key购买 nike

给定这个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

我可以创建一个字典,其中包含列列表作为值,如下所示:

d = {df.loc[idx, 'first']: [df.loc[idx, 'second'], df.loc[idx, 'third']] for idx in range(df.shape[0])}

但是我如何创建一个字典,比如说,一个包含 firstsecond 作为键的元组?

结果是:

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...

最佳答案

您需要通过set_index 创建MultiIndex然后调用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'}

关于python - Pandas:创建一个以元组为键的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42276588/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com