【发布时间】:2018-06-07 21:42:58
【问题描述】:
我正在使用 2.1.9.3717 版本的 Canopy 运行其他人编写的代码,绘制直方图以对以前的数据系列进行引导分析,每次都遇到此错误。我尝试重新安装numpy或将已知数字变量更改为int而不是float,但没有任何效果。我对编程真的很陌生,这给我带来了很多困惑。代码如下:
from __future__ import division
import numpy as np
import matplotlib as mpl
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import pylab
import lmfit
import math
import random
from scipy.optimize import curve_fit
from scipy.optimize import leastsq
from scipy.stats import gamma
import csv
import ntpath
import pandas as pd
end = 0
bslist = []
path = '/Users/....../'
proj_name = '180607'
data_input = '180607_BootstrapGlobal.csv'
bs_param_CIs=pd.DataFrame()
#Extract data supplied as a .csv file
fn = ntpath.basename(path)
datafile = fn.split(".")[0]
datafile2 = path+data_input
bootstrap=pd.read_csv(datafile2, sep=None, header=0,engine= 'python')
def ctend_plot(point, ci, y, label): #function to define central tendency and error bars
plt.plot(ci,[y,y],"-", color="g", linewidth=4, label=label)
plt.plot(point, y, "o", color="r", markersize=10)
for column in bootstrap:
fig = plt.figure()
ax = fig.add_subplot(111)
bsmean = np.mean(bootstrap[column])
bsstd = np.std(bootstrap[column])
bsmed= np.median(bootstrap[column]) # HERE WE ARE USING THE MEDIAN TO CALC CI
plt.hist(bootstrap[column],bins=math.ceil(np.sqrt(len(bootstrap[column]))))
bsmean_y = 10
lower=2.5 #CHANGE lower and upper TO CALC SOMETHING OTHER THAN 95% CI!
upper=97.5
percCI= int(upper-lower)
bsiqr= np.percentile(bootstrap[column],[lower,upper])
ctend_plot(bsmed,bsiqr,bsmean_y-8, "%s %i CI" %(column, percCI))
plt.legend();
lgd = ax.legend(bbox_to_anchor=(1.05,1.05), loc=5, borderaxespad=0)
plt.savefig('{0}{1}_{2}%CI_{3}.png'.format(path, proj_name,percCI,column), dpi=300)
plt.clf()
plt.close()
bs_param_CI_one=pd.DataFrame({ 'Param' : ['%s'%(column)],
'Mean': ['%f'%(bsmean)],
'Median': ['%f'%(bsmed)],
'%s_CI'%(percCI): ['%s'%(bsiqr)] })
bs_param_CI_one=bs_param_CI_one[['Param','Mean','Median','%s_CI'%(percCI)]]
frames =[bs_param_CIs, bs_param_CI_one]
bs_param_CIs=pd.concat(frames)
bs_param_CIs.to_csv("{0}{1}_bootstrap_CIs.csv".format(path, proj_name),index=None)
还有输出:
TypeErrorTraceback (most recent call last)
/Users/.../bootstrap_figs.py in <module>()
44 bsstd = np.std(bootstrap[column])
45 bsmed= np.median(bootstrap[column]) # HERE WE ARE USING THE MEDIAN TO CALC CI
---> 46 plt.hist(bootstrap[column],bins=math.ceil(np.sqrt(len(bootstrap[column]))))
47 bsmean_y = 10
48 lower=2 #CHANGE lower and upper TO CALC SOMETHING OTHER THAN 95% CI!
/Users/yasmin_m/Library/Enthought/Canopy/edm/envs/User/lib/python2.7/site-packages/matplotlib/pyplot.pyc in hist(x, bins, range, normed, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, hold, data, **kwargs)
3080 histtype=histtype, align=align, orientation=orientation,
3081 rwidth=rwidth, log=log, color=color, label=label,
-> 3082 stacked=stacked, data=data, **kwargs)
3083 finally:
3084 ax._hold = washold
/Users/yasmin_m/Library/Enthought/Canopy/edm/envs/User/lib/python2.7/site-packages/matplotlib/__init__.pyc in inner(ax, *args, **kwargs)
1890 warnings.warn(msg % (label_namer, func.__name__),
1891 RuntimeWarning, stacklevel=2)
-> 1892 return func(ax, *args, **kwargs)
1893 pre_doc = inner.__doc__
1894 if pre_doc is None:
/Users/yasmin_m/Library/Enthought/Canopy/edm/envs/User/lib/python2.7/site-packages/matplotlib/axes/_axes.pyc in hist(self, x, bins, range, normed, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, **kwargs)
6190 # this will automatically overwrite bins,
6191 # so that each histogram uses the same bins
-> 6192 m, bins = np.histogram(x[i], bins, weights=w[i], **hist_kwargs)
6193 m = m.astype(float) # causes problems later if it's an int
6194 if mlast is None:
/Users/yasmin_m/Library/Enthought/Canopy/edm/envs/User/lib/python2.7/site-packages/numpy/lib/function_base.py in histogram(a, bins, range, normed, weights, density)
727
728 # Initialize empty histogram
--> 729 n = np.zeros(bins, ntype)
730 # Pre-compute histogram scaling factor
731 norm = bins / (mx - mn)
TypeError: 'float' object cannot be interpreted as an index
【问题讨论】:
-
这段代码是为 Python 3 编写的吗?看起来它可能依赖于
math.ceil的 Python 3 行为。 -
这里有什么需要使用 Python 2 的理由吗?将工作的 3.x 代码反向移植到 2.x 曾经是您必须一直做的事情,因为您需要的某些库或其他库尚未更新,但在 2018 年很少有充分的理由这样做(您更多可能具有仅适用于 3.x 的依赖项,而不是仅适用于 2.x 的依赖项。
-
Canopy 2.1 同时支持 Python 2 和 Python 3。正如其他人所指出的,您可能正在尝试在 Python 2 环境中运行 Python 3 代码。要切换环境,请参阅docs.enthought.com/canopy/2.1/configure/…
-
@user2357112 不,它是用 Python2 编写的。这是建模过程的最后一步,所有其他步骤都是用 Python2 编写的。