Search code examples
pythonpandasdataframeconcatenation

Add all column values repeated of one data frame to other in pandas


Having two data frames:

df1 = pd.DataFrame({'a':[1,2,3],'b':[4,5,6]})

   a  b
0  1  4
1  2  5
2  3  6

df2 = pd.DataFrame({'c':[7],'d':[8]})

   c  d
0  7  8

The goal is to add all df2 column values to df1, repeated and create the following result. It is assumed that both data frames do not share any column names.

   a  b  c  d
0  1  4  7  8
1  2  5  7  8
2  3  6  7  8

Solution

  • If there are strings columns names is possible use DataFrame.assign with unpack Series created by selecing first row of df2:

    df = df1.assign(**df2.iloc[0])
    print (df)
       a  b  c  d
    0  1  4  7  8
    1  2  5  7  8
    2  3  6  7  8
    

    Another idea is repeat values by df1.index with DataFrame.reindex and use DataFrame.join (here first index value of df2 is same like first index value of df1.index):

    df = df1.join(df2.reindex(df1.index, method='ffill'))
    print (df)
       a  b  c  d
    0  1  4  7  8
    1  2  5  7  8
    2  3  6  7  8
    

    If no missing values in original df is possible use forward filling missing values in last step, but also are types changed to floats, thanks @Dishin H Goyan:

    df = df1.join(df2).ffill()
    print (df)
       a  b    c    d
    0  1  4  7.0  8.0
    1  2  5  7.0  8.0
    2  3  6  7.0  8.0