Python 如果行中的任何值等于零,则在 Pandas 数据框中删除行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27020312/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:20:16  来源:igfitidea点击:

Drop row in pandas dataframe if any value in the row equals zero

pythonpandas

提问by azuric

How do I drop a row if any of the values in the row equal zero?

如果行中的任何值等于零,如何删除一行?

I would normally use df.dropna() for NaN values but not sure how to do it with "0" values.

我通常将 df.dropna() 用于 NaN 值,但不确定如何使用“0”值来实现。

采纳答案by acushner

i think the easiest way is looking at rows where all values are not equal to 0:

我认为最简单的方法是查看所有值都不等于 0 的行:

df[(df != 0).all(1)]

回答by DSM

You could make a boolean frame and then use any:

您可以制作一个布尔框架,然后使用any

>>> df = pd.DataFrame([[1,0,2],[1,2,3],[0,1,2],[4,5,6]])
>>> df
   0  1  2
0  1  0  2
1  1  2  3
2  0  1  2
3  4  5  6
>>> df == 0
       0      1      2
0  False   True  False
1  False  False  False
2   True  False  False
3  False  False  False
>>> df = df[~(df == 0).any(axis=1)]
>>> df
   0  1  2
1  1  2  3
3  4  5  6

回答by Arash

Assume a simple DataFrame as below:

假设一个简单的 DataFrame 如下:

df=pd.DataFrame([1,2,0,3,4,0,9])

Pick non-zero values which turns all zero values into nan and remove nan-values

选择将所有零值转换为 nan 并删除 nan 值的非零值

df=df[df!=0].dropna()

df

Output:

输出:

    0
0   1.0
1   2.0
3   3.0
4   4.0
6   9.0

回答by Non_linear

Although it is late, someone else might find it helpful. I had similar issue. But the following worked best for me.

虽然已经晚了,但其他人可能会发现它有帮助。我有类似的问题。但以下对我来说效果最好。

df =pd.read_csv(r'your file')
df =df[df['your column name'] !=0]

reference: Drop rows with all zeros in pandas data framesee @ikbel benabdessamad

参考: 删除熊猫数据框中全为零的行,请参阅@ikbel benabdessamad