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

Pandas convert_objects弃用后替代方案报错的处理咨询

Solution for Converting "-" to 0 in DataFrame (Avoiding Deprecated Methods)

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')) runs pd.to_numeric on each column (a Series, which is 1D) individually. The errors='coerce' flag turns any value that can't be converted to a number (like "-") into NaN.
  • replace(np.nan, 0) cleans up those NaNs 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:21:05