如何使用Pandas和Matplotlib移除DataFrame指定列含0的行?
Hey there! Let's break down why your current code isn't doing what you need, and get you a working solution right away.
The Problem With Your Original Approach
Your line df.loc[(df!=0).any(1)] checks if any column in the row has a non-zero value. That means it'll keep rows where your target two columns have 0, but other columns have non-zero values—which is exactly what you don't want. You need to focus only on the two specific columns you care about, not all 8 columns.
The Correct Solution
You want to keep rows where both of your target columns are not 0 (since you want to remove any row where either one has 0). Here's how to do it:
First, define the names of the two columns you want to check (replace these with your actual column names):
target_columns = ['Column_A', 'Column_B'] # 换成你表格里的真实列名
Then use one of these two methods to filter your DataFrame:
Method 1: Explicit Boolean Conditions
This is straightforward and easy to read:
# 只保留两列都不为0的行 clean_df = df.loc[(df[target_columns[0]] != 0) & (df[target_columns[1]] != 0)]
Method 2: Using all() for Conciseness
If you prefer a more compact approach, you can use all() to check that all values in the target columns are non-zero for each row:
# 检查目标列的每一行是否所有值都不为0 clean_df = df[(df[target_columns] != 0).all(axis=1)]
Why This Works
df[target_columns] != 0creates a boolean DataFrame that only includes your two target columns, where each cell isTrueif the value isn't 0, andFalseif it is..all(axis=1)checks each row to see if all the values in that row (for the target columns) areTrue—meaning neither column has a 0.- The resulting boolean series is used to filter your original DataFrame, keeping only the rows you want.
Quick Verification
After filtering, you can confirm it worked by running:
# 检查清理后的DataFrame中目标列是否还有0 print(clean_df[target_columns].eq(0).any())
This should return False for both columns if everything worked correctly.
内容的提问来源于stack exchange,提问作者Paul Blessing

