1

I have a dataframe like this

some_info   THIS_info
abd          set_1
def          set_1
www          set_1
qqq          set_2
wws          set_2
2222         set_3

and another dataframe like this

THIS_info   this_algo
set_1        algo_1
set_2        algo_2
set_3        algo_2

I want to add a column to the first dataframe, based on the info on "THIS_info" so that I can get

some_info   THIS_info  this_algo
abd          set_1      algo_1
def          set_1      algo_1
www          set_1      algo_1
qqq          set_2      algo_2
wws          set_2      algo_2
2222         set_3      algo_2

Is there a way to achieve this?

KansaiRobot
  • 7,564
  • 11
  • 71
  • 150

2 Answers2

2

You can use the merge function to join the two dataframes (df1 and df2):

df1 = pd.merge(df1, df2, how='left', on='THIS_info')
print(df1)

Output:

some_info   THIS_info  this_algo
abd          set_1      algo_1
def          set_1      algo_1
www          set_1      algo_1
qqq          set_2      algo_2
wws          set_2      algo_2
2222         set_3      algo_2

Note that parameters how and on are optional in this example, but are useful in a more general situation.

Mattravel
  • 1,358
  • 1
  • 15
1

You can use merge function, like

import pandas as pd

df_left = pd.DataFrame({
    "some_info": ["abd", "def", "www", "qqq", "wws", "2222"],
    "THIS_info": ["set_1", "set_1", "set_1", "set_2", "set_2", "set_3"]
})
df_right = pd.DataFrame({
    "THIS_info": ["set_1", "set_2", "set_3"],
    "this_algo": ["algo_1", "algo_2", "algo_2"]
})
df = df_left.merge(df_right, on="THIS_info", how="left")
print(df)

Then you can get output:

  some_info THIS_info this_algo
0       abd     set_1    algo_1
1       def     set_1    algo_1
2       www     set_1    algo_1
3       qqq     set_2    algo_2
4       wws     set_2    algo_2
5      2222     set_3    algo_2
EeyoreLee
  • 81
  • 5