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

如何将Pandas中带$符号的object类型列转为可计算数值类型?

Fixing the TypeError When Summing a Currency Column in Pandas

Got it, let's work through this problem step by step. The core issue here is your WASHING column holds string values with a dollar sign ($), which pd.to_numeric can't parse directly—this is why you ended up with all NaN values when using errors='coerce'. Here's how to fix it properly:

Step 1: Clean the currency strings first

You need to strip out non-numeric characters (like the $) from each value before converting to a numeric type. Run this code:

# Remove the dollar sign; add .replace(',', '') if you have values like $1,234.56
df['WASHING'] = df['WASHING'].str.replace('$', '', regex=False)

Using regex=False prevents accidental regex matching issues (since $ is a special regex symbol for end-of-string).

Step 2: Convert the cleaned column to numeric type

Now that the strings are just numeric text (like 45.00), you can safely convert them to floats (or integers if you don't need decimals):

df['WASHING'] = pd.to_numeric(df['WASHING'], errors='coerce')

The errors='coerce' flag will turn any remaining invalid values (like unforeseen non-numeric strings) into NaN—you can decide later whether to drop these, fill with 0, or investigate further.

Step 3: Sum the column

With the column now in numeric format, your sum will work without errors:

Wash_amount = df['WASHING'].sum()

How to check for edge cases

If you still run into issues, use these checks to spot problematic values:

  • View unique values to identify unexpected formats:
    print(df['WASHING'].unique())
    
  • Check for null values or non-string entries:
    print(df['WASHING'].isnull().sum())
    print(df[df['WASHING'].apply(lambda x: not isinstance(x, str))])
    
  • Verify your cleaning worked with a sample of values:
    print(df['WASHING'].head(10))
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:44:01