Pandas:如果多列中有多个为零,则删除行 [英] Pandas: drop row if more than one of multiple columns is zero

查看:229
本文介绍了Pandas:如果多列中有多个为零,则删除行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的数据框:

I have a dataframe as such:

     col0   col1  col2  col3
ID1    0      2     0     2
ID2    1      1     2     10
ID3    0      1     3     4

我想删除多次包含零的行.

I want to remove rows that contain zeros more than once.

我尝试过:

cols = ['col1', etc]
df.loc[:, cols].value_counts()

但这仅适用于系列而不适用于数据框.

But this only works for series and not dataframes.

df.loc[:, cols].count(0) <= 1

只返回布尔值.

我觉得我已经接近第二次尝试了.

I feel like I'm close with the 2nd attempt here.

推荐答案

应用条件并计算 True 值.

Apply the condition and count the True values.

(df == 0).sum(1)

ID1    2
ID2    0
ID3    1
dtype: int64

df[(df == 0).sum(1) < 2]

     col0  col1  col2  col3
ID2     1     1     2    10
ID3     0     1     3     4

或者,将整数转换为 bool 并求和.更直接一点.

Alternatively, convert the integers to bool and sum that. A little more direct.

# df[(~df.astype(bool)).sum(1) < 2]
df[df.astype(bool).sum(1) > len(df.columns)-2]  # no inversion needed

     col0  col1  col2  col3
ID2     1     1     2    10
ID3     0     1     3     4

<小时>

为了性能,你可以使用np.count_nonzero:

# df[np.count_nonzero(df, axis=1) > len(df.columns)-2]
df[np.count_nonzero(df.values, axis=1) > len(df.columns)-2]

     col0  col1  col2  col3
ID2     1     1     2    10
ID3     0     1     3     4

<小时>

df = pd.concat([df] * 10000, ignore_index=True)

%timeit df[(df == 0).sum(1) < 2]
%timeit df[df.astype(bool).sum(1) > len(df.columns)-2]
%timeit df[np.count_nonzero(df.values, axis=1) > len(df.columns)-2]

7.13 ms ± 161 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
4.28 ms ± 120 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
997 µs ± 38.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

这篇关于Pandas:如果多列中有多个为零,则删除行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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