如何在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
相关产品推荐
相关产品推荐

