基于多个条件删除行 Python Pandas
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29017525/
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
Deleting rows based on multiple conditions Python Pandas
提问by fyr91
I want to delete rows when a few conditions are met:
我想在满足几个条件时删除行:
For instance, a random DataFrame is generated:
例如,生成一个随机数据帧:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(10, 4), columns=['one', 'two', 'three', 'four'])
print df
one instance of table is shown as below:
表的一个实例如下所示:
one two three four
0 -0.225730 -1.376075 0.187749 0.763307
1 0.031392 0.752496 -1.504769 -1.247581
2 -0.442992 -0.323782 -0.710859 -0.502574
3 -0.948055 -0.224910 -1.337001 3.328741
4 1.879985 -0.968238 1.229118 -1.044477
5 0.440025 -0.809856 -0.336522 0.787792
6 1.499040 0.195022 0.387194 0.952725
7 -0.923592 -1.394025 -0.623201 -0.738013
8 -1.775043 -1.279997 0.194206 -1.176260
9 -0.602815 1.183396 -2.712422 -0.377118
I want to delete rows based on the conditions that:
我想根据以下条件删除行:
Row with value of col 'one', 'two', or'three' greater than 0; andvalue of col 'four' less than 0 should be deleted.
列 'one'、'two'或'three' 的值大于 0 的行;并且应该删除小于 0 的 col 'four' 值。
Then I tried to implement as follows:
然后我尝试实现如下:
df = df[df.one > 0 or df.two > 0 or df.three > 0 and df.four < 1]
However, resulting in a error message as follow:
但是,导致错误消息如下:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Could someone help me on how to delete based on multiple conditions?
有人可以帮助我如何根据多个条件删除吗?
回答by Brionius
For reasons that aren't 100% clear to me, pandas
plays nice with the bitwise logical operators |
and &
, but not the boolean ones or
and and
.
对于不是100%我清楚的原因,pandas
起到很好的与位逻辑运算符|
和&
,而不是布尔类型的or
和and
。
Try this instead:
试试这个:
df = df[(df.one > 0) | (df.two > 0) | (df.three > 0) & (df.four < 1)]