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

如何从Pandas DataFrame中筛选包含至少一个非零值的列?

Solution for Filtering Columns with At Least One Non-Zero Value in Pandas

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 != 0 creates a boolean DataFrame where each cell is True if the value isn't zero, False otherwise.
  • .any() checks each column and returns True if there's at least one True (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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:43:03