如何从Pandas DataFrame中筛选包含至少一个非零值的列?
Hey there! I get your frustration—filtering rows is straightforward, but targeting columns with non-zero values can feel tricky at first. Let's fix this with your sample DataFrame.
First, let's recreate your data to work with:
import pandas as pd data = { 'Type': ['Seg0', 'Seg1'], 'ADR': [0.0, 0.0], 'ALE': [0.0, 0.0], 'ALF': [0.0, 0.5], 'AME': [0.0, 0.0] } df = pd.DataFrame(data)
The Simple One-Liner Solution
You can use a combination of boolean masking and the .any() method to select only columns that have at least one non-zero value:
filtered_df = df.loc[:, (df != 0).any()]
Let's break this down:
df != 0creates a boolean DataFrame where each cell isTrueif the value isn't zero,Falseotherwise..any()checks each column and returnsTrueif there's at least oneTrue(i.e., at least one non-zero value) in that column.df.loc[:, ...]uses that boolean result to slice the DataFrame, keeping only the columns that meet the condition.
What the Output Looks Like
Running this code will give you exactly what you want:
Type ALF 0 Seg0 0.0 1 Seg1 0.5
Alternative Approach: Drop All-Zero Columns
If you prefer, you can also achieve the same result by dropping columns that are entirely zero:
filtered_df = df.drop(columns=df.columns[(df == 0).all()])
Here, (df == 0).all() identifies columns where every value is zero, and drop() removes them from the DataFrame.
Both methods work perfectly—pick whichever makes more sense to you!
内容的提问来源于stack exchange,提问作者user3476463

