检查字典中的数据帧值,将关键字追加到新列中



我正在尝试检查字典中的行值是否匹配,并将键附加到新列中。

示例:

group_ID = {
'Group A':[4738, 4812],
'Group B':[5888, 6551],
'Group C':[4487, 7888]
}
user_data = [['Alex',4812],['Bob',4487],['Clarke',5888]]
sample_df = pd.DataFrame(user_data,columns=['Name','User ID'])
print(sample_df)
Name  User ID
0    Alex     4812
1     Bob     4487
2  Clarke     5888

使用此示例,如果sample_df中的"用户ID"在字典"group_ID"中具有匹配值,则我希望添加第三列,以反映密钥名称,如下所示:

Name  User ID Group ID
0    Alex     4812  Group A
1     Bob     4487  Group C
2  Clarke     5888  Group B

提前感谢您的帮助!

这能完成任务吗:

matches = []
# iterate over each user ID
for user_id in sample_df['User ID']:
# go through the items in the dictionary and append to `matches` list
matches.extend([key for key, values in group_ID.items() if user_id in values])
if matches:
# if matches not empty, then add a new column
sample_df['group_ID'] = matches

尝试:

tmp = {i: k for k, v in group_ID.items() for i in v}
sample_df["Group ID"] = sample_df["User ID"].map(tmp)
print(sample_df)

打印:

Name  User ID Group ID
0    Alex     4812  Group A
1     Bob     4487  Group C
2  Clarke     5888  Group B

最新更新