使用gumbel_r.fit()报错‘float’ object has no attribute ‘sqrt’求解决
Gumbel分布拟合报错:AttributeError: 'float' object has no attribute 'sqrt'
你尝试用scipy.stats.gumbel_r的fit()和ppf()方法处理多组数据,但运行时出现上述错误,原代码如下:
原数据读取代码
contoh1 = pd.read_excel('data.xlsx',header=None,sheet_name='Sheet7') dn=contoh1.columns y1 =contoh1[dn[1]][37:43] y2 =contoh1[dn[2]][21:43] y3 =contoh1[dn[3]][21:43] y4 =contoh1[dn[4]][1:43] y5 =contoh1[dn[5]][22:44] gmb=[y1,y2,y3,y4,y5]
原循环处理代码
ch_res={} parameter_9={} Rx_9={} Fx_9 = 0.5 for i in range (len(gmb)): ch_res[i] = np.array(gmb,dtype=object) parameter_9[i]= gumbel_r.fit(ch_res[i]) Rx_9[i]= gumbel_r.ppf(Fx_9,*parameter_9[i])
错误原因
循环中的ch_res[i] = np.array(gmb,dtype=object)是核心问题:
- 你把整个
gmb列表(包含所有5组数据)转成了object类型的数组,而非当前循环对应的单组数据gmb[i] gmb中的元素是pandas Series,直接转object数组会导致gumbel_r.fit()无法正确解析数据类型,内部计算时触发类型错误
修正后的代码
优化的数据读取部分(可选,简化重复代码)
import pandas as pd import numpy as np from scipy.stats import gumbel_r contoh1 = pd.read_excel('data.xlsx', header=None, sheet_name='Sheet7') # 用iloc直接按行、列索引切片,写法更清晰规范 gmb = [ contoh1.iloc[37:43, 1], # 对应原y1:第2列(索引1),行37-42 contoh1.iloc[21:43, 2], # 对应原y2:第3列(索引2),行21-42 contoh1.iloc[21:43, 3], # 对应原y3:第4列(索引3),行21-42 contoh1.iloc[1:43, 4], # 对应原y4:第5列(索引4),行1-42 contoh1.iloc[22:44, 5] # 对应原y5:第6列(索引5),行22-43 ]
修正后的循环处理代码
ch_res = {} parameter_9 = {} Rx_9 = {} Fx_9 = 0.5 for i in range(len(gmb)): # 将当前组的Series转为浮点型numpy数组,确保fit方法能正确处理 ch_res[i] = gmb[i].to_numpy(dtype=np.float64) # 拟合Gumbel分布参数 parameter_9[i] = gumbel_r.fit(ch_res[i]) # 计算对应分位数 Rx_9[i] = gumbel_r.ppf(Fx_9, *parameter_9[i])
关键修正点
- 循环中仅处理当前索引的单组数据
gmb[i],而非整个gmb列表 - 使用
to_numpy(dtype=np.float64)明确转换数据类型,避免object数组导致的解析错误 - 用
iloc替代原有的列索引+行切片写法,更符合pandas的标准用法
内容的提问来源于stack exchange,提问作者iyya
相关产品推荐
相关产品推荐

