筛选包含至少一个零的Pandas数据框中的行 [英] Filtering for rows in a Pandas dataframe containing at least one zero

查看:417
本文介绍了筛选包含至少一个零的Pandas数据框中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试删除Pandas数据框中所有两列中都不为零的行。我的数据帧的索引从0到620。这是我的代码:

I am trying to delete all rows in a Pandas data frame that don't have a zero in either of two columns. My data frame is indexed from 0 to 620. This is my code:

for index in range(0, 621):
    if((zeroes[index,1] != 0) and (zeroes[index,3] != 0)):
        del(zeroes[index,])

我一直遇到关键错误。
KeyError:(0,1)

I keep getting a key error. KeyError: (0, 1)

我的教练建议我更改范围以进行测试,以查看数据框中是否有不良行。是的我检查了数据框的尾部,然后将范围更改为(616,621)。然后我得到了关键错误:(616,1)。

My instructor suggested I change the range to test to see if I have bad lines in my data frame. I did. I checked the tail of my dataframe and then changed the range to (616, 621). Then I got the key error: (616, 1).

有人知道我的代码有什么问题或为什么我遇到键错误吗?

Does anyone know what is wrong with my code or why I am getting a key error?

此代码还会产生(0,1)的关键错误:

This code also produces a key error of (0,1):

index = 0
while (index < 621):
    if((zeroes[index,1] != 0) and (zeroes[index,3] != 0)):
        del(zeroes[index,])
index = index + 1


推荐答案

不要使用手册 for 在这里循环。您的错误可能是由于 df .__ getitem __((x,y))引起的,实际上就是 df [x,y] 调用没有意义。

Don't use a manual for loop here. Your error probably occurs because df.__getitem__((x, y)), which is effectively what df[x, y] calls, has no significance.

相反,请使用向量化操作和布尔索引。例如,要删除第1列或第3列不等于0的行:

Instead, use vectorised operations and Boolean indexing. For example, to remove rows where either column 1 or 3 do not equal 0:

df = df[df.iloc[:, [1, 3]].eq(0).any(1)]

eq(0)创建一个布尔值的数据框,该值指示等于零,而 any(1)过滤器用于包含以下内容的行 True 值。

This works because eq(0) creates a dataframe of Boolean values indicating equality to zero and any(1) filters for rows with any True values.

完整格式为 df.iloc [:, [1, 3]]。eq(0).any(axis = 1) df.iloc [:, [1,3]]。eq(0).any( axis ='columns')更加清晰。请参阅 pd.DataFrame.any 了解更多详情。

The full form is df.iloc[:, [1, 3]].eq(0).any(axis=1), or df.iloc[:, [1, 3]].eq(0).any(axis='columns') for even more clarity. See the docs for pd.DataFrame.any for more details.

这篇关于筛选包含至少一个零的Pandas数据框中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆