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

如何在Pandas中将object类型的Year列转为float并持久化?

Solution to Persist Year Column Type Conversion in Pandas

Hey there! I totally get why this is confusing—when you run pd.to_numeric(data["Year"], errors='coerce') on its own, it just returns a temporary Series with the converted float values, but doesn't actually update the original DataFrame. Here's how you fix it:

The Fix: Assign the Converted Series Back to the Original Column

You need to explicitly save the converted result back to the Year column in your DataFrame. This overwrites the original object-type column with the new float-type values:

import pandas as pd

# Read your data
data = pd.read_csv(r"data1.csv", sep=None, engine='python')

# Check initial data types
print("Original data types:")
print(data.dtypes)

# Convert Year column AND save the change to the DataFrame
data["Year"] = pd.to_numeric(data["Year"], errors='coerce')

# Verify the conversion worked
print("\nUpdated data types:")
print(data.dtypes)

Why This Works

  • pd.to_numeric() generates a new Series with the converted values, but doesn't modify the original DataFrame unless you assign it back.
  • The errors='coerce' flag will turn any non-numeric values in the Year column into NaN (which is fine for float type, since float supports missing values).

Bonus: Save the Updated Data (Optional)

If you want to keep these changes for future analysis, save the modified DataFrame to a new CSV file:

# Save without the index column to keep your CSV clean
data.to_csv("updated_data1.csv", index=False)

After running this, your Year column will stay as float type for all subsequent operations on the data DataFrame.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:09:07