[英]Merge a filling DataFrame into a mask, based on index and columns
使用以下“掩碼”數據幀:
>>> mask
city value_1 value_2
index
0 London 10 NaN
1 Paris NaN 21
2 Paris 30 NaN
3 Paris NaN NaN
4 Berlin 3 5
5 Berlin NaN 10
6 New York NaN NaN
以及以下“填充”框架:
>>> filling
value_1 value_2
London 1100 2100
Paris 1150 2200
Berlin NaN 3000
New York 5000 NaN
如何根據city
和列將filling
合並到mask
,以便生成的 DataFrame 變為:
>>> result
city value_1 value_2
index
0 London 10 2100
1 Paris 1150 21
2 Paris 30 2200
3 Paris 1150 2200
4 Berlin 3 5
5 Berlin NaN 10
6 New York 5000 NaN
從概念上講,從任何值mask
是NaN
是易於通過的值被“填充” filling
其中兩個其匹配city
和其列( value_1
或value_2
)。
我正在努力解決的部分是讓DataFrame.merge()
考慮到索引(這里是city
)和所有列。 兩者都可以,但要獲得預期的結果,我似乎需要兩者。
編輯:
我嘗試了以下方法:
>>> expanded = mask[[]].join(filling, on='city')
>>> mask.merge(expanded)
但這只是讓我返回mask
,並且所有來自expanded
值都被簡單地忽略(即使目標單元格是NaN
)。
嘗試使用reindex
filling
fillna
:
mask.fillna(filling.reindex(mask.city).set_index(mask.index))
輸出:
city value_1 value_2
index
0 London 10.0 2100.0
1 Paris 1150.0 21.0
2 Paris 30.0 2200.0
3 Paris 1150.0 2200.0
4 Berlin 3.0 5.0
5 Berlin NaN 10.0
6 New York 5000.0 NaN
DataFrame.update
,我們可以使用帶有overwrite=False
DataFrame.update
。
注意:我們將方法分開在不同的行中,因為更新就位。
mask = mask.set_index("city")
mask.update(filling, overwrite=False)
mask = mask.reset_index()
city value_1 value_2
0 London 10.0 2100.0
1 Paris 1150.0 21.0
2 Paris 30.0 2200.0
3 Paris 1150.0 2200.0
4 Berlin 3.0 5.0
5 Berlin NaN 10.0
6 New York 5000.0 NaN
您還可以使用專為此目的設計的combine_first
:
print (mask.set_index("city").combine_first(filling))
value_1 value_2
Berlin 3.0 5.0
Berlin NaN 10.0
London 10.0 2100.0
New York 5000.0 NaN
Paris 1150.0 21.0
Paris 30.0 2200.0
Paris 1150.0 2200.0
如果您需要保留原始順序, reset_index
執行reset_index
並稍后對其進行排序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.