Pandas中如何将非空Series转换类型后赋值回原DataFrame
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

