我正在嘗試將兩個資料框合并在一起以替換可能的缺失值。例如:
df1:
Fruit Price
Apple 5
Banana 7
Orange 4
df2:
Fruit Price
Pear 3
result:
Fruit Price
Apple 5
Banana 7
Orange 4
Pear 3
我已經使用 concat 方法來執行此操作并且它有效,但是當兩個資料幀具有相同的列而不是具有兩個重復值時,我想使用第一個 df 中的資料并忽略第二個 df。例如:
df1:
Fruit Price
Apple 5
Banana 7
Orange 4
Pear 6
df2:
Fruit Price
Pear 3
result:
Fruit Price
Apple 5
Banana 7
Orange 4
Pear 6
我該如何做到這一點,以便它適用于兩個示例?
uj5u.com熱心網友回復:
您可以在 Fruit 列上使用concat和鏈接。drop_duplicates只要始終確保將您希望值保留的資料框作為第一個引數復制到concat:
# Case 1
>>> pd.concat([df1b,df2]).drop_duplicates('Fruit')
Fruit Price
0 Apple 5
1 Banana 7
2 Orange 4
0 Pear 3
# Case 2
>>> pd.concat([df1,df2]).drop_duplicates('Fruit')
Fruit Price
0 Apple 5
1 Banana 7
2 Orange 4
3 Pear 6
設定
df1 = pd.DataFrame({'Fruit':['Apple','Banana','Orange','Pear'],
'Price':[5,7,4,6]})
df1b = pd.DataFrame({'Fruit':['Apple','Banana','Orange'],
'Price':[5,7,4]})
df2 = pd.DataFrame({'Fruit':['Pear'],
'Price':[3]})
uj5u.com熱心網友回復:
這是一種方法:合并 df1 和 df2 并僅保留不匹配的那些并與第一個連接
當 Fruit 已經存在時,第二個將是空的,不會被合并
pd.concat([df1,
df2.merge(df1, on='Fruit', how='left', suffixes=('','_y')).query('Price_y.isnull()').drop(columns='Price_y')]
)
Fruit Price
0 Apple 5
1 Banana 7
2 Orange 4
0 Pear 3
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/496095.html
