简体   繁体   中英

Pandas How to mapping two dataframes without remove unique value?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM