Home > Net >  Pandas How to mapping two dataframes without remove unique value?
Pandas How to mapping two dataframes without remove unique value?

Time:05-24

I have two dataframes like this.

df1

  id    value1
0  002     10
1  003     10
2  004     20
3  005     20

df2

   id        value2
0  001        100
1  002        200
2  003        150

I merge dataframe like with this code.

df3 = pd.merge(df1, df2, left_on='id', right_on='id')

The output of this code is.

  id    value1 value2
0  002     10   200
1  003     10   150

I don't want to remove unique data. I want result like this.

  id    value1  value2
  001     100     
  002     10     200
  003     10     150
  004     20
  005     20

How to mapping two data frames without remove unique value?

CodePudding user response:

You can try how=outer

df3 = pd.merge(df1, df2, on='id', how='outer')
print(df3)

   id  value1  value2
0   2    10.0   200.0
1   3    10.0   150.0
2   4    20.0     NaN
3   5    20.0     NaN
4   1     NaN   100.0
  • Related