SOK
SOK

Reputation: 1792

How to map to multiple values in a dictionary in pandas

I have the following pandas df:

Name
Jack
Alex
Jackie
Susan

i also have the following dict:

d = {'Jack':['Male','22'],'Alex':['Male','26'],'Jackie':['Female','28'],'Susan':['Female','30']}

I would like to add in two colums for Gender and Age so that my df returns:

Name      Gender    Age
Jack      Male       22
Alex      Male       26
Jackie    Female     28
Susan     Female     30

I have tried:

df['Gender'] = df.Name.map(d[0])
df['Age'] = df.Name.map(d[1])

but no such luck. Any ideas or help would be muhc appreciated! Thanks!

Upvotes: 1

Views: 1687

Answers (4)

jezrael
jezrael

Reputation: 862691

Solutions working well also if no match in dictionary like:

d = {'Alex':['Male','26'],'Jackie':['Female','28'],'Susan':['Female','30']}


print (df)
     Name  Gender  Age
0    Alex    Male   26
1    Jack     NaN  NaN
2  Jackie  Female   28
3   Susan  Female   30

Use DataFrame.from_dict from your dictionary and add to column Name by DataFrame.join, advantage is if more columns in input data all working same way:

df = df.join(pd.DataFrame.from_dict(d, orient='index', columns=['Gender','Age']), on='Name')
print (df)
     Name  Gender Age
0    Jack    Male  22
1    Alex    Male  26
2  Jackie  Female  28
3   Susan  Female  30

Your solution should working if create 2 dictionaries:

d1 = {k:v[0] for k,v in d.items()}
d2 = {k:v[1] for k,v in d.items()}

df['Gender'] = df.Name.map(d1)
df['Age'] = df.Name.map(d2)
print (df)
     Name  Gender Age
0    Jack    Male  22
1    Alex    Male  26
2  Jackie  Female  28
3   Susan  Female  30

Upvotes: 0

Mayank Porwal
Mayank Porwal

Reputation: 34056

Use pd.DataFrame constructor with Series.map and use pd.concat to concat with df:

In [2696]: df = pd.concat([df,pd.DataFrame(df.Name.map(d).tolist(), columns=['Gender', 'Age'])], axis=1)

In [2695]: df
Out[2696]: 
     Name  Gender Age
0    Jack    Male  22
1    Alex    Male  26
2  Jackie  Female  28
3   Susan  Female  30

Upvotes: 1

Sivaram Rasathurai
Sivaram Rasathurai

Reputation: 6333

Take all the values of the dictionary

d = {'Jack':['Male','22'],'Alex':['Male','26'],'Jackie':['Female','28'],'Susan':['Female','30']}

value_list = list(d.values())
df = pd.DataFrame(value_list, columns =['Gender', 'Age'])
print(df)  

Upvotes: 1

Muhammad Junaid Haris
Muhammad Junaid Haris

Reputation: 452

df['Gender'] = df.Name.map(lambda x: d[x][0])
df['Age'] = df.Name.map(lambda x: d[x][1])

Upvotes: 2

Related Questions