Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append two DataFrames with different number of rows, populating the shorter one

Tags:

python

pandas

df1 = pd.DataFrame({'var1': [1], 'var4': ['P']})
df2 = pd.DataFrame({'var2': list('abcd'), 'var3': range(4)})

With the above data frames I'd like to join them with populating the rows of df1. So the expected output should look like below:

df3 = pd.DataFrame({'var1': [1] * 4, 'var4': ['P'] * 4, 'var2': list('abcd'), 'var3': range(4)})

   var1 var4 var2  var3
0     1    P    a     0
1     1    P    b     1
2     1    P    c     2
3     1    P    d     3

Is this possible to do without a manual replication of df1 rows?

like image 495
jakes Avatar asked Nov 24 '25 23:11

jakes


1 Answers

Let us try assign

df2.assign(**df1.iloc[0].to_dict())
  var2  var3  var1 var4
0    a     0     1    P
1    b     1     1    P
2    c     2     1    P
3    d     3     1    P
like image 101
BENY Avatar answered Nov 27 '25 15:11

BENY



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!