[英]Return key corresponding to the tuple with smallest third value from dictionary
[英]If value from dictionary is in dataframe, return specific corresponding key
我是 python 和 pandas 的新手,所以希望在这里得到一些指导。 给定字典和 DataFrame 如果字典中的值存在于 DataFrame 中,我将尝试提取特定的对应键。
例如:
Input:
dict = {'Happy': [1, 2], 'Sad': [3, 4, 5]}
people = {'Name': ['John','Tom','Helen'],'Status': [3,2,5]}
df = pd.DataFrame(people, columns = ['Name', 'Status'])
Expected Output:
output_dict = {'John': 'Happy', 'Tom': 'Happy', 'Helen': 'Sad'}
这是我到目前为止所尝试的:
for key, value in dict.items():
for val in value:
for row in df.itertuples():
if row.status == val:
return {df['Name']:key}
但是由于某种原因,我最后的 dict 总是返回为空。
让我们尝试修改您的dict
,然后使用replace
或map
out = df.set_index('Name').Status.replace({z : x for x , y in d.items() for z in y } ).to_dict()
{'John': 'Sad', 'Tom': 'Happy', 'Helen': 'Sad'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.