python pandas选择两列(不)相等的行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45039937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python pandas select rows where two columns are (not) equal
提问by kkjoe
hsp.loc[hsp['Len_old'] == hsp['Len_new']]
I try this code, it's working.
我试试这个代码,它的工作。
But I tried these three
但我试过这三个
hsp.loc[hsp['Type_old'] == hsp['Type_new']]
hsp.loc[hsp['Type_old'] != hsp['Type_new']]
hsp.loc[hsp['Len_old'] != hsp['Len_new']]
They are not working.
他们不工作。
My data table hsp is like
我的数据表 hsp 就像
id Type_old Type_new Len_old Len_new
1 Num Num 15 15
2 Num Char 12 12
3 Char Num 10 8
4 Num Num 4 5
5 Char Char 9 10
Is there a better approach to select rows where two columns are not queal.
有没有更好的方法来选择两列不冲突的行。
采纳答案by piRSquared
Ways to be confused by ==
versus !=
when comparing pd.Series
比较时被==
vs混淆的方法!=
pd.Series
As expected
正如预期的那样
df[['Len_old', 'Len_new']].assign(NE=df.Len_old != df.Len_new)
Len_old Len_new NE
0 15 15 False
1 12 12 False
2 10 8 True
3 4 5 True
4 9 10 True
But if one of the column's values were strings!
但是如果列的值之一是字符串!
df[['Len_old', 'Len_new']].assign(NE=df.Len_old.astype(str) != df.Len_new)
Len_old Len_new NE
0 15 15 True
1 12 12 True
2 10 8 True
3 4 5 True
4 9 10 True
Make sure both are the same types.
确保两者是相同的类型。
回答by VinceP
Use the complement operator~
使用补运算符~
hsp.loc[~(hsp['Type_old'] == hsp['Type_new'])]
which gives:
这使:
id Type_old Type_new Len_old Len_new
1 2 Num Char 12 12
2 3 Char Num 10 8
When dealing with Boolean operations, the complement operator is a handy way to invert True
with False
当布尔运算处理,补运算符是反转的便捷方式True
与False