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

Pandas中如何将非空Series转换类型后赋值回原DataFrame

Fixing Pandas Assignment for Nullable Integer Columns

Hey there! I totally get where you're stuck—let's break down why your assignment isn't working and how to fix it to get the result you want.

Why Your Current Code Isn't Working

The issue boils down to data types in Pandas. Your original B column is a float64 type because it contains NaN (which is inherently a float value). When you convert non-null values to integers and assign them back, Pandas automatically converts those integers back to floats to keep the entire column's dtype consistent. That's why you don't see any visible change—those values are still stored as floats (even if they look like integers in the print output).

The Solution: Use Pandas' Nullable Integer Type

Pandas has a built-in nullable integer dtype (Int64, note the capital "I") that supports both integer values and NaN. This is exactly what you need to keep your integers as integers while preserving the missing values.

Simple One-Line Fix

You don't even need to filter non-null values first—just convert the entire column directly:

df['B'] = df['B'].astype('Int64')

Let's test this with your sample DataFrame:
Original DataFrame:

id      A        B
0  50000  12413  32885.0
1  50001   2040  43737.0
3  50002   2040  28015.0
4  50003   2040      NaN
5  50004   2040  28565.0

After running the code above, you'll get exactly what you want:

id      A        B
0  50000  12413  32885
1  50001   2040  43737
3  50002   2040  28015
4  50003   2040     NaN
5  50004   2040  28565

If you check the column dtype with print(df.dtypes), you'll see B is now Int64—perfect for holding integers and nulls together.

If You Want to Stick to Filtered Assignment

If you still prefer to only modify non-null values explicitly, you first need to convert the column to Int64 before assigning:

# First convert the column to nullable integer type
df['B'] = df['B'].astype('Int64')
# Now assign the integer values (though this step is redundant since astype already handled it)
df.loc[df['B'].notnull(), 'B'] = df.loc[df['B'].notnull(), 'B'].astype(int)

But the first one-line method is far cleaner and more efficient.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:15:33