0

I have 2 pandas dataframe and I want to search through strings in column A of dataframe 1 with the strings in column A of dataframe 2. If there's a match I want to append the corresponding value from dataframe 2 into a new column in dataframe 1, if there is no match I want to append the new value adding the string from column A in dataframe 2 to the bottom of column A in dataframe 1 and include a value of zero in column B.

My df1 looks like:

Column A          | Column B 
apple             |   87   
orange            |   75
pear              |   105

and df2 looks like:

Column A          | Column B 
apple             |   95   
orange            |   105
pear              |   134
banana            |   99

Therefore I'd like output df to be:

Column A          | Column B | Column C
apple             |   87     |   95
orange            |   75     |   105
pear              |   105    |   134
banana            |   0      |   99

I was trying to use a for loop and:


Search_Strings_List = df2['Column A'].tolist()
Value_List = df1['Column B'].tolist()

for search_string in Search_Strings_List:
    
    for value in Value_List
    
        df1['Column C'] = df['Column A'].str.contains('search_string')*value

But that isn't giving me the desired output. Any input would be great

MRaff16
  • 5
  • 5
  • Use: `df3 = df1.merge(df2, on='Column A', how='outer').fillna(0).rename(columns={'Column B_x': 'Column B', 'Column B_y': 'Column C'})` – Mayank Porwal Nov 26 '21 at 20:56

0 Answers0