![](/img/trans.png)
[英]How to drop Pandas DataFrame rows with condition to keep specific column value
[英]How to only keep dataframe rows that shares same value on a specific column
我有兩個要比較的數據框,但首先我想斷言第一列(我用作索引)對於兩者都是相同的。
df1
A B C D E
0 a 10 5 18 20
1 b 9 18 11 13
2 c 8 7 12 5
3 z 6 5 3 90
df2
A B C D E
0 a 10 45 10 22
1 b 99 18 11 13
2 e 8 7 12 5
3 f 6 5 3 90
我只想保留 A 列中的值在兩個數據框中的行。 所以我希望 output 像 df1 和 df2 一樣。
df3
A B C D E
0 a 10 5 18 20
1 b 9 18 11 13
df4
A B C D E
0 a 10 45 10 22
1 b 99 18 11 13
我還想檢索已刪除的行。
刪除_df
A B C D E
0 c 8 7 12 5
1 z 6 5 3 90
2 e 8 7 12 5
3 f 6 5 3 90
我現在已經試過了:
df3 = df1[df1['A'].isin(df2['A'])]
df4 = df2[df2['A'].isin(df1['A'])]
這似乎可行,但我不確定,但我仍然想檢索 df3 和 df1 之間的區別(以及分別是 df4 和 df2 )
您可以做的一件事是通過True
for indicator
進行outer
合並:
>>> df1.merge(df2, on='A', indicator=True, how='outer', suffixes=('1', '2',))
A B1 C1 D1 E1 B2 C2 D2 E2 _merge
0 a 10.0 5.0 18.0 20.0 10.0 45.0 10.0 22.0 both
1 b 9.0 18.0 11.0 13.0 99.0 18.0 11.0 13.0 both
2 c 8.0 7.0 12.0 5.0 NaN NaN NaN NaN left_only
3 z 6.0 5.0 3.0 90.0 NaN NaN NaN NaN left_only
4 e NaN NaN NaN NaN 8.0 7.0 12.0 5.0 right_only
5 f NaN NaN NaN NaN 6.0 5.0 3.0 90.0 right_only
這樣,您將獲得該行是否來自兩列或僅來自左/右之一的信息。
使用isin
:
df1.loc[df1.A.isin(df2.A)]
A B C D E
0 a 10 5 18 20
1 b 9 18 11 13
isin
返回用於過濾的 boolean 系列:
df1.A.isin(df2.A)
0 True
1 True
2 False
3 False
Name: A, dtype: bool
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.