0

I have a DataFrame, containing "keys" and "values". In another datframe, i have only the keys. I want this second dataframe to fill a new column if the keys can be matched. Better to see on the example:

df = pd.DataFrame({'text':['bla','bla2','hi'], 'value':['hello','morning','random']})

df1 = pd.DataFrame({'text':['bla','x','hi','y','bla2','hi','bla']})

and i want the output to look like this:

df1
    text     value
0   bla      hello
1   x           
2   hi       random  
3   y
4   bla2     morning
5   hi       random
6   bla      hello

i thought this would be easiest if i create a dictionary from df with text as key and value as values, which i do with this: y=pd.Series(df.value.values,index=df.text).to_dict() which would look like this: y={'bla': 'hello', 'bla2': 'morning', 'hi': 'random'} but now i dont know how to do the "matching"

user11638654
  • 305
  • 2
  • 12

1 Answers1

0

With Dataframe.merge function:

In [70]: df.merge(df1, how='right', on='text').fillna('')                                                                       
Out[70]: 
   text    value
0   bla    hello
1   bla    hello
2  bla2  morning
3    hi   random
4    hi   random
5     x         
6     y         
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105