Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging a dataframe with another dataframe with constant values from the first dataframe

I would like to merge two data frames, df1 and df2:

import pandas as pd

df1 = pd.DataFrame({
    'A': ['a'],
    'B': ['b'],
    'C': ['c']
})

df2 = pd.DataFrame({
    'W': [1, 2, 3],
    'X': [4, 5, 6],
    'Y': [7, 8, 9],
    'Z': [10, 11, 12]
}) 

df1: (will always have only one row)

enter image description here

df2: (can have any number of rows)

enter image description here

In a way that all the columns of df1 are added to the df2 dataframe with all the rows having the same values present in the df1 dataframe.

I have tried:

df3 = pd.concat([df1,df2], sort=False, axis=1)

But this is giving me NaN's:

enter image description here

But i want all the rows to have the same constant value that is present in df1 like:

enter image description here

I would also like to maintain having the new columns from df1 be before the columns of df2 as above. What might be the most efficient way to achieve this.

like image 872
Ayush Shrivastava Avatar asked May 25 '26 20:05

Ayush Shrivastava


2 Answers

We can do an outer merge on an artificially created key:

df1.assign(key=1).merge(df2.assign(key=1), on='key').drop('key', axis=1)

   A  B  C  W  X  Y   Z
0  a  b  c  1  4  7  10
1  a  b  c  2  5  8  11
2  a  b  c  3  6  9  12
like image 121
Erfan Avatar answered May 28 '26 11:05

Erfan


Use DataFrame.assign with selecting first row and then change order of columns by DataFrame.reindex:

df3 = df2.assign(**df1.iloc[0]).reindex(df1.columns.union(df2.columns, sort=False),axis=1)
print (df3)
   A  B  C  W  X  Y   Z
0  a  b  c  1  4  7  10
1  a  b  c  2  5  8  11
2  a  b  c  3  6  9  12

Or add rows to df1 by df2.index with method='ffill':

df3 = pd.concat([df1.reindex(df2.index, method='ffill'),df2], sort=False, axis=1)
print (df3)
   A  B  C  W  X  Y   Z
0  a  b  c  1  4  7  10
1  a  b  c  2  5  8  11
2  a  b  c  3  6  9  12
like image 40
jezrael Avatar answered May 28 '26 10:05

jezrael