Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 基于列值在dataframe中删除行_Python_Pandas - Fatal编程技术网

Python 基于列值在dataframe中删除行

Python 基于列值在dataframe中删除行,python,pandas,Python,Pandas,我有这样一个数据帧: cols = [ 'a','b'] df = pd.DataFrame(data=[[NaN, -1, NaN, 34],[-32, 1, -4, NaN],[4,5,41,14],[3, NaN, 1, NaN]], columns=['a', 'b', 'c', 'd']) 当列“a”和“b”为非负时,我希望检索所有行,但如果其中任何一行或所有行都丢失,我希望保留它们 结果应该是 a b c d 2 4 5 41 14 3 3 NaN

我有这样一个数据帧:

cols = [ 'a','b']
df = pd.DataFrame(data=[[NaN, -1, NaN, 34],[-32, 1, -4, NaN],[4,5,41,14],[3, NaN, 1, NaN]], columns=['a', 'b', 'c', 'd'])
当列“a”和“b”为非负时,我希望检索所有行,但如果其中任何一行或所有行都丢失,我希望保留它们

结果应该是

   a   b   c   d
2  4   5  41  14
3  3 NaN   1 NaN
我已经试过了,但是没有达到预期的效果

df[(df[cols]>0).all(axis=1) | df[cols].isnull().any(axis=1)]

IIUC,你真的想要

>>> df[((df[cols] > 0) | df[cols].isnull()).all(axis=1)]
   a   b   c   d
2  4   5  41  14
3  3 NaN   1 NaN
现在你会得到“如果它们都是正的”或“任何都是空的”。您需要“如果它们都是(正或空)”。(将
>0
替换为
=0
以获得非负性。)

由于NaN不是正数,我们可以通过翻转条件来简化,并使用

>>> df[~(df[cols] <= 0).any(axis=1)]
   a   b   c   d
2  4   5  41  14
3  3 NaN   1 NaN

>>df[~(df[cols]IIUC,你真的想要

>>> df[((df[cols] > 0) | df[cols].isnull()).all(axis=1)]
   a   b   c   d
2  4   5  41  14
3  3 NaN   1 NaN
现在您得到的是“如果它们都是正的”或“任何都是空的”。您想要的是“如果它们都是(正的或空的)”(将
>0
替换为
=0
表示非负性。)

由于NaN不是正数,我们可以通过翻转条件来简化,并使用

>>> df[~(df[cols] <= 0).any(axis=1)]
   a   b   c   d
2  4   5  41  14
3  3 NaN   1 NaN

>>df[~(df[cols]ha!我要用翻转版本准确回答!哈!我要用翻转版本准确回答!