'How to apply conditions to 2 different dataframes

I have 2 different DataFrames (df, df_2), where I want to apply a condition:

If the raw of df_2 == df then display the value of the df in a different column of df_2.

df_2.loc[df_2['Fecha'] == df['Fecha'], 'name_match'] = df['Fecha'] ## does NOT work

Could you please tell me what is the best method to use?



Solution 1:[1]

Not clear if you only want the values to be copied in case the whole column of df matches that of df_2 or for only those values that match. I assumed the latter. What I would do is to create a boolean column that indicates if it is equal or not.

df = pd.DataFrame([[12,5,7], [13,7,4]], columns=['fecha', 'abc', 'def'])
df_2 = pd.DataFrame([[12,5,7], [13,99,1]], columns=['fecha', 'abc', 'def'])
print('df:')
print(df)
print('df_2:')
print(df_2)

df:
   fecha  abc  def
0     12    5    7
1     13    7    4
df_2:
   fecha  abc  def
0     12    5    7
1     13   99    1

then I would just add a col and fill it based on equality per row:

col = 'fecha'
ncol = f"name_match_{col}"
df_2[ncol] = (df_2[col] == df[col])
col = 'abc'
ncol = f"name_match_{col}"
df_2[ncol] = (df_2[col] == df[col])

gives

print(df_2)
fecha  abc  def  name_match_fecha  name_match_abc
0     12    5    7              True            True
1     13   99    1              True           False

The you can use that to fill other columns.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Flag