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

使用Pandas转换加密货币数据列为float时报ValueError的问题求解

报错原因排查
  • 核心问题:你爬取的CoinGecko页面数值列默认带$前缀(格式如$3,821.45),仅移除逗号没有处理$符号,非数字字符存在直接触发转换失败
  • 代码缩进错误:data初始化、币种识别、表格行遍历的逻辑没有放在for url in url_list的循环体内,仅能拿到最后一个链接的爬取结果
  • 转换逻辑缺陷:你注释了单字段预处理的代码,直接调用astype批量转换类型,没有提前清洗所有特殊字符
  • 潜在异常:部分行可能存在空值、N/A等无效标识,未做容错处理也会触发转换报错
可行修复方案

先对所有待转换的数值列做全量特殊字符清洗,再用带容错的方法转换为浮点数,修正缩进问题后完整代码如下:

import requests
from bs4 import BeautifulSoup
import pandas as pd

url_list = ['https://www.coingecko.com/en/coins/ethereum/historical_data/usd?start_date=2021-08-06&end_date=2021-09-05#panel',
            'https://www.coingecko.com/en/coins/cardano/historical_data/usd?start_date=2021-08-06&end_date=2021-09-05#panel',
            'https://www.coingecko.com/en/coins/chainlink/historical_data/usd?start_date=2021-08-06&end_date=2021-09-05#panel']

dfList = []

for url in url_list:
    response = requests.get(url)
    soup = BeautifulSoup(response.text , 'html.parser')
    data = []
    coin = url.split("/")[5].upper()
    # 遍历表格行
    for row in soup.select('tbody tr'):
        data.append(
            dict(zip([f'{x.text}_{coin}' for x in soup.select('thead th')], [x.text.strip() for x in row.select('th,td') ]))
        )
    # 生成单币种DataFrame
    df = pd.DataFrame(data)
    df['Date_'+str(coin)] = pd.to_datetime(df['Date_'+str(coin)])
    # 批量清洗数值列并转换类型
    for col in ['Market Cap_','Volume_','Open_','Close_']:
        col_name = col + str(coin)
        # 依次移除$符号、逗号,再转浮点数,无效值转为NaN
        df[col_name] = pd.to_numeric(df[col_name].str.replace('$','').str.replace(',',''), errors='coerce')
    dfList.append(df)

# 可后续合并所有币种数据
# final_df = pd.concat(dfList, axis=1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 12:36:04