How do I get a value of other dataframe based on same date?

Viewed 319

Take df_1:

df_1 = pd.DataFrame({'date':['2021-01-25','2021-01-26','2021-01-27'],
                     'a':[np.nan,np.nan,np.nan]})
         date   a
0  2021-01-25 NaN
1  2021-01-26 NaN
2  2021-01-27 NaN

And take df_2:

df_2 = pd.DataFrame({'date':['2021-01-27','2021-01-28','2021-01-29'],
                     'b':[1,2,3]})
         date  b
0  2021-01-27  1
1  2021-01-28  2
2  2021-01-29  3

I need to fill column a value getting column b value, if they have the same dates.

5 Answers

This worked for me:

df_1.a = df_1.date.map(df_2.set_index(df_2.date)['b'])

You may merge the two dataframes based on date and extract the desired column from second dataframe. Like this:

df_1.merge(df_2,how='left', on='date')[['date', 'b']].rename(columns={'b': 'a'})

Try this:

d = df_2.set_index('date').squeeze().to_dict()
df_1['a'] = df_1['a'].fillna(df_1['date'].map(d))

You can set 'date' as the index in both data frames and fill missing values using the method fillna:

 df_1.set_index('date')['a'].fillna(df_2.set_index('date')['b']).reset_index()

Output:

         date    a
0  2021-01-25  NaN
1  2021-01-26  NaN
2  2021-01-27  1.0

I think you should use pd.merge:

pd.merge(df_1['date'],df_2, on='date', how='outer').dropna(axis = 0)
Related