gpt4 book ai didi

python - 使用相同的键、多个值追加到字典

转载 作者:行者123 更新时间:2023-11-30 22:00:54 24 4
gpt4 key购买 nike

试图了解这里最好的想法/实践是什么..我有一个包含不同地点的面试官的数据框..我想创建一个字典或某种数据结构来保存面试官的姓名,然后保存每个坐标我们对他们的采访有几点看法。我正在使用的数据框的一个示例是这样的:

    interview       longitude        latitude
1 A1 34.2 90.2
2 A1 54.2 23.5
6 A1 NaN NaN
7 A2 NaN NaN
8 A2 NaN NaN
9 A2 23.1 38.2
10 A2 -23.7 -98.4

我基本上想要一个包含“A1”的字典,它包含(34.2, 90.2)、(54.2, 23.5),而“A2”将包含(23.1, 39.2)、(-23.7, -98.4)。

    location_dict = {}
for name, group in df.groupby('Interviewer'):
minidf = group[['Interviewer','Longitude','Latitude']].dropna()
for index, row in minidf.iterrows():
location_dict[name]=(row['Longitude'], row['Latitude'])

我的逻辑有点偏离,但我没有任何方法“附加”到字典,所以我的字典只输出 iterrows 最后一次迭代的数据......我将如何解决这个问题?

最佳答案

使用 groupby 的一个解决方案:

def zipper(row):
return list(zip(row['longitude'], row['latitude']))

res = df.dropna(subset=['longitude', 'latitude'])\
.groupby('interview').apply(zipper).to_dict()

# {'A1': [(34.2, 90.2), (54.2, 23.5)],
# 'A2': [(23.1, 38.2), (-23.7, -98.4)]}

另一个使用 collections.defaultdict :

from collections import defaultdict

res = defaultdict(list)
for row in df.dropna(subset=['longitude', 'latitude']).itertuples(index=False):
res[row.interview].append((row.longitude, row.latitude))

由于defaultdictdict的子类,因此通常不需要进一步的操作。

关于python - 使用相同的键、多个值追加到字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54201340/

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