Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check dataframe value to dictionary, append key to new column

I am trying to check a row value for a match in a dictionary and append the key to a new column.

Example:

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

Using this example, if ‘User ID’ in sample_df has a matching value in dictionary ‘group_ID’ then I would like to add a third column reflecting the key name like below:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Thanks in advance for the help!

>Solution :

Does this do the job:

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading