You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pandas中删除含任意0值的整行?已尝试代码未达预期

Solution: Remove Rows with Any Zero Value in Any Column

Got it, let's sort this out for you. The issue with your current code is that (df!=0).any(axis=1) checks if at least one column in the row is non-zero, so it only filters out rows where every single value is 0. But what you need is to keep rows where all columns have no zeros—so we need to flip that logic to use all() instead of any().

Step 1: Correct Code

Here's the adjusted line that will remove any row containing a 0 in any column:

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

Let's Test It with Your Example Data

First, let's recreate your input DataFrame:

import pandas as pd

data = {
    'kt': [1,2,3,4,5],
    'b': [1,2,3,0,5],
    'tt': [1,2,3,4,5],
    'mky': [1,2,0,0,5],
    'depth': [4,2,3,0,0]
}
df = pd.DataFrame(data)

Applying the corrected code:

df_filtered = df.loc[(df != 0).all(axis=1)]
print(df_filtered)

Expected Output

kt  b  tt  mky  depth
0   1  1   1    1      4
1   2  2   2    2      2

That's exactly the result you were looking for! The all(axis=1) ensures that every value in the row is non-zero—so any row with even one 0 gets excluded.

内容的提问来源于stack exchange,提问作者Ahamed Moosa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:22:29