1

I have an empty dataframe df1

import numpy as np
import pandas as pd

df1 = pd.DataFrame(columns=['A','B','C','D','E'])

df1
A   B   C   D   E

I want to merge or update this dataframe with another dataframe df2

df2 = pd.DataFrame({ 'B': [1,2,3],
                     'D': [4,5,6],
                     'E': [7,8,9]})
df2
    B   D   E
0   1   4   7
1   2   5   8
2   3   6   9

to get a merged or updated dataframe as

    A   B   C   D   E
0   NaN 1   NaN 4   7
1   NaN 2   NaN 5   8
2   NaN 3   NaN 6   9

Besides, efficiency is required because I have a long df1 and df2.

Any good idea? Thank you.

2
  • 1
    Try this: df2.reindex(columns=df1.columns) Commented Jan 10, 2023 at 5:33
  • At start you are saying you have empty df1 at end you are saying its very long df1. which one is it ? Commented Jan 10, 2023 at 5:45

2 Answers 2

3

Use reindex:

df1 = df2.reindex(columns=df1.columns)

Output:

    A  B   C  D  E
0 NaN  1 NaN  4  7
1 NaN  2 NaN  5  8
2 NaN  3 NaN  6  9
Sign up to request clarification or add additional context in comments.

Comments

2

try this

import pandas as pd
pd.concat((df1, df2))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.