Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Combine and fill a Pandas Dataframe with the single row of another

If I have two dataframes:

df1:

df1 = pd.DataFrame({'A':[10,20,15,30,45], 'B':[17,33,23,10,12]})


    A   B
0  10  17
1  20  33
2  15  23
3  30  10
4  45  12

df2:

df2 = pd.DataFrame({'C':['cat'], 'D':['dog'], 'E':['emu'], 'F':['frog'], 'G':['goat'], 'H':['horse'], 'I':['iguana']})


     C    D    E     F     G      H       I
0  cat  dog  emu  frog  goat  horse  iguana

How do I combine the two dataframes and fill df1 whereby each row is a replicate of df2 ?

Here is what I have so far. The code works as intended, but if I were to have hundreds of columns, then I would anticipate there would be a much easier way than my current method:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Current Code:

df1 = df1.assign(C = lambda x: df2.C[0],
                 D = lambda x: df2.D[0],
                 E = lambda x: df2.E[0],
                 F = lambda x: df2.F[0],
                 G = lambda x: df2.G[0],
                 H = lambda x: df2.H[0],
                 I = lambda x: df2.I[0])

Expected output:

    A   B    C    D    E     F     G      H       I
0  10  17  cat  dog  emu  frog  goat  horse  iguana
1  20  33  cat  dog  emu  frog  goat  horse  iguana
2  15  23  cat  dog  emu  frog  goat  horse  iguana
3  30  10  cat  dog  emu  frog  goat  horse  iguana
4  45  12  cat  dog  emu  frog  goat  horse  iguana

>Solution :

Use DataFrame.assign with Series by first row:

df = df1.assign(**df2.iloc[0])
print (df)
    A   B    C    D    E     F     G      H       I
0  10  17  cat  dog  emu  frog  goat  horse  iguana
1  20  33  cat  dog  emu  frog  goat  horse  iguana
2  15  23  cat  dog  emu  frog  goat  horse  iguana
3  30  10  cat  dog  emu  frog  goat  horse  iguana
4  45  12  cat  dog  emu  frog  goat  horse  iguana
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading