如何在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 intoNaN(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
相关产品推荐
相关产品推荐

