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

处理英国新冠疫情数据调用np.log时出现ufunc循环类型错误如何解决

问题原因

你在对DataFrame做转置、行列拼接的过程中,nuovi_casi列的数值类型被自动转换为了object类型,列内存储的是Python原生int对象,Numpy的通用函数(ufunc)不支持对Python原生int做向量化的对数计算,因此触发报错。

解决方案

快速修复

在对数计算代码前增加类型转换逻辑,将列转换为数值类型即可:

sts = ts.nuovi_casi
sts.index.name = None
# 新增行:转成浮点型,适配numpy计算
sts = sts.astype(float)
ts_log = np.log(1+sts).dropna()

也可以直接使用pandas内置的类型转换方法避免非数值异常:

sts = pd.to_numeric(sts, errors='coerce')

优化数据处理逻辑(从根源避免类型错误)

你原有的转置、拼接行列的处理逻辑过于复杂,很容易触发pandas的自动类型转换,建议改用宽表转长表的标准方法处理时序数据,不会出现类型异常问题:

pd.set_option('display.max_rows', None)          
df = pd.read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv')
# 筛选英国本土数据,排除海外领地
df = df[(df["Country/Region"]=="United Kingdom") & (df["Province/State"].isna())]
# 宽表转长表,直接生成日期、确诊数两列结构
df = df.melt(id_vars=["Province/State","Lat","Long","Country/Region"], var_name="date", value_name="nuovi_casi")
df['nuovi_casi'] = df['nuovi_casi'] + 10000
# 后续计算
ts = df[['nuovi_casi']].dropna()
sts = ts.nuovi_casi
sts.index.name = None
ts_log = np.log(1+sts).dropna()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 03:54:03