0

So i got my dataframe (df1):

Number    Name       Gender  Hobby
122       John       Male      -
123       Patrick    Male      -
124       Rudy       Male      -

I want to add data to hobby based on number column. Assuming i've got my list of hobby based on its number on different dataframe. Like Example (df2):

Number    Hobby
124       Soccer
...         ...
...         ...

and df3 :

Number    Hobby
122       Basketball
...         ...
...         ...

How can i achieve this dataframe:

Number    Name       Gender  Hobby
122       John       Male    Basketball
123       Patrick    Male      -
124       Rudy       Male    Soccer

So far i've already tried this following solutions :

Select rows from a DataFrame based on values in a column in pandas

but its only selecting some data. How can i update the 'Hobby' column ? Thanks in advance.

4
  • Simple assignment df['Hobby'] = hobby Commented Jan 2, 2018 at 5:18
  • What if the hobby index its not always same index in list? Commented Jan 2, 2018 at 5:22
  • im facing 2 dataframe here. each dataframe has different rows. i cant use that assignment. Commented Jan 2, 2018 at 5:23
  • how do you know which item belongs to which Number. Build a dictionary, list is of no use here then. Commented Jan 2, 2018 at 5:26

1 Answer 1

0

You can use map, merge and join will also achieve it

df['Hobby']=df.Number.map(df1.set_index('Number').Hobby)
df
Out[155]: 
   Number     Name Gender   Hobby
0     122     John   Male     NaN
1     123  Patrick   Male     NaN
2     124     Rudy   Male  Soccer
Sign up to request clarification or add additional context in comments.

2 Comments

thank you. what if i've got another df and i want map it into multiple dataframe. in this case just df1, can i add with df1 and df2 as well?
@Fregy yes you can repeat above

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.