[英]Python: how to merge two pandas dataframes with condition
我有兩個數據框如下
df1
A B
0 0 3
1 0 2
2 1 5
3 1 3
4 2 5
5 'Ciao' 'log'
6 3 4
df2
A B
0 0 -1
1 0 20
2 1 -2
3 1 33
4 2 17
我想合並這兩個數據幀,以便 if A==0
保留df1
的值,否則保留df2
的值。
最后,我想要類似下面的東西
df2
A B
0 0 3
1 0 2
2 1 -2
3 1 33
4 2 17
假設數據幀對齊(並且df1
中的重復索引 3 是錯字),您不需要merge
,而是使用where
的條件:
out = df1.where(df1['A'].eq(0), df2)
Output:
A B
0 0 3
1 0 2
2 1 -2
3 1 33
4 2 17
注意。 如果你真的想要合並,你必須進一步解釋合並的邏輯並提供一個重要的例子。
更新示例:
您似乎仍然有部分對齊的索引,但想要獲得交集:
out = (df1.where(df1['A'].eq(0), df2)
.loc[df1.index.intersection(df2.index)]
)
或者:
out = (df1.reindex_like(df2)
.where(df1['A'].eq(0), df2)
)
output:
A B
0 0.0 -1.0
1 0.0 20.0
2 1.0 -2.0
3 1.0 33.0
4 2.0 17.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.