using pandas dataframes fill rows based on condition if both values are same in two dataframes

Viewed 33

am having two dataframes , first dataframe has 3 columns user_id, value, year_month columns second dataframe has 4 columns sep_month,01,02,03 .

extract & create month from year_month column, now with month column need to create & fill rows from other dataframe based on condition if sep_month & month values are same

Input Dataframe 
df_1
###
     user_id date_month     value   
1        1    2020-01       1000   
2        1    2020-02       2000   
3        1    2020-03       6000   

4        2    2020-01       1800   
5        2    2020-02       2700   
6        2    2020-03       3600   

df_2
###
     month  01    02      03
      01    1.5   0.2     3.6
      02    3.6   1.6      0
      03    6.3   5.1     7.2

Output Dataframe
###
     user_id date_month     value   01   02      03
1        1    2020-01       1000   1.5   0.2     3.6
2        1    2020-02       2000   3.6   1.6      0
3        1    2020-03       6000   6.3   5.1     7.2

4        2    2020-01       1800   1.5   0.2     3.6
5        2    2020-02       2700   3.6   1.6      0
6        2    2020-03       3600   6.3   5.1     7.2

1 Answers

You can first split the date_month field and do join

df_1[['year','month']] = df_1['date_month'].str.split('-',expand=True)
result = pandas.df_1.merge(df_1,df_2, on='month', how='left')
Related