Home > Back-end >  Add column Dataframe A to each row DataframeB
Add column Dataframe A to each row DataframeB

Time:01-09

I have a dataframe 1 that contains date

Date

01/01/2022
02/01/2022
03/01/2022
04/01/2022

and i have a dataframe 2

User 
A 
B
C

and i want to merge this two dataframe by adding the first dataframe to each row of the second dataframe as the output below

User     date
A     01/01/2022
A     02/01/2022
A     03/01/2022
A     04/01/2022
B     01/01/2022
B     02/01/2022
B     03/01/2022
B     04/01/2022
C     01/01/2022
C     02/01/2022
C     03/01/2022
C     04/01/2022

CodePudding user response:

Try cross merge.

df1:

   A
0  1
1  2
2  3

df2:

    B
0  aa
1  bb
2  cc

df1.merge(df2, cross=True)

   A   B
0  1  aa
1  1  bb
2  1  cc
3  2  aa
4  2  bb
5  2  cc
6  3  aa
7  3  bb
8  3  cc

CodePudding user response:

If both of your DataFrames are one column each, you can do something like the following:

df1['Date'] = df1['User'].apply(lambda x: df2['Date'].values)
df1.explode('Date')

Result:

  User        Date
0    A  01/01/2022
0    A  02/01/2022
0    A  03/01/2022
0    A  04/01/2022
1    B  01/01/2022
1    B  02/01/2022
1    B  03/01/2022
1    B  04/01/2022
2    C  01/01/2022
2    C  02/01/2022
2    C  03/01/2022
2    C  04/01/2022
  •  Tags:  
  • Related