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

如何在Pandas DataFrame中根据指定列的空值删除行?

Dropping Rows with Null/NaN in Column 'b' Using Pandas

No problem at all—this is a straightforward task in Pandas, and there are a couple of clean ways to do exactly what you need (only removing rows where column b has nulls, ignoring nulls in a and c).

Method 1: Using dropna() (the most common approach)

The dropna() method is built for this kind of row removal, and the subset parameter lets you target only the column you care about:

import pandas as pd

# Replace 'df' with your actual DataFrame name
df = df.dropna(subset=['b'])

This line tells Pandas to scan only column b for NaN/Null values, and drop any row where that condition is met. Columns a and c can have as many nulls as they want—they won't affect which rows get kept.

If you want to modify your original DataFrame directly instead of creating a new one, add the inplace=True argument:

df.dropna(subset=['b'], inplace=True)

Just note that using inplace=True means you won't have a copy of the original DataFrame anymore, so use it if you don't need to keep the original data.

Method 2: Boolean Indexing (more explicit for some)

Another way to do this is by filtering rows where column b is not null, using notna():

df = df[df['b'].notna()]

This works by creating a boolean mask where each entry is True if b has a non-null value, then using that mask to select only those rows. The end result is identical to the dropna() method—it's just a matter of which syntax you prefer.

Quick Example to Test

Let's make a sample DataFrame to see this in action:

# Sample data with nulls in all columns
data = {
    'a': [1, 2, None, 4],
    'b': [5, None, 7, 8],
    'c': [None, 10, 11, None]
}
df = pd.DataFrame(data)

# After running either method above, your DataFrame will look like this:
#    a    b     c
# 0  1.0  5.0  NaN
# 2  NaN  7.0  11.0
# 3  4.0  8.0  NaN

Notice the row where b was None (index 1) is gone, but rows with nulls in a or c are still there—perfect for your use case.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:37:13