Pandas convert_objects弃用后替代方案报错的处理咨询
Hey there! Let's fix this issue properly—since convert_objects is deprecated, we'll use the recommended pd.to_numeric approach without hitting that TypeError. Here's the breakdown:
Why Your Current pd.to_numeric Attempt Failed
The error happens because pd.to_numeric is designed for 1-dimensional data (like lists, Series, or 1D arrays), not full DataFrames. You need to apply it column-by-column to handle your 2D table.
Step-by-Step Solution
Assuming your DataFrame has column names (A/B/C/D/E) as strings (which we'll keep intact), here's how to convert all data rows to numeric values, turn "-" into 0, and keep everything ready for arithmetic operations:
First, make sure you have the necessary imports:
import pandas as pd import numpy as np
Then run these lines:
# Convert each column to numeric, turning non-numeric values (like "-") into NaN new_table = new_table.apply(lambda col: pd.to_numeric(col, errors='coerce')) # Replace all NaN values with 0 new_table = new_table.replace(np.nan, 0)
If Your "First Row" Is the Row Index (Not Column Names)
If you meant the first column (with values like 1, 2, "-") is your string-based row index, adjust the code to preserve that index first:
# Set the first column as your row index (keeps it as string type) new_table = new_table.set_index('A') # Process the remaining columns exactly as before new_table = new_table.apply(lambda col: pd.to_numeric(col, errors='coerce')).replace(np.nan, 0)
Why This Works
apply(lambda col: pd.to_numeric(col, errors='coerce'))runspd.to_numericon each column (a Series, which is 1D) individually. Theerrors='coerce'flag turns any value that can't be converted to a number (like "-") intoNaN.replace(np.nan, 0)cleans up thoseNaNs by turning them into 0, which is safe for arithmetic operations.- Your column names (or row index, if you used the second approach) stay as strings exactly as you need.
Bonus: Verify the Result
To confirm everything is set up correctly, check the data types of your columns:
print(new_table.dtypes)
All data columns should show int64 or float64, while your column names/index remain strings.
内容的提问来源于stack exchange,提问作者Marx Babu

