在Canopy环境中,Python错误“'float'对象不能被解释为索引”

时间:2018-06-07 21:42:59

标签: python numpy canopy

我正在使用Canopy的2.1.9.3717版本来运行其他人编写的代码,绘制直方图以用于先前数据系列的自举分析,并且每次都会遇到此错误。我尝试了所有重新安装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

2 个答案:

答案 0 :(得分:2)

你说:

  

我尝试重新安装numpy或将已知的数字变量更改为int而不是float

...但你似乎并没有真正转换为int,只是在它们上面调用math.ceil。这不会改变类型:

  

将x 的上限作为浮动 返回,这是一个大于或等于x的最小整数值。

你想要的可能是int(math.ceil(…)),它将天花板作为浮点数,然后将该int转换为浮点数(通过截断它,但因为你已经天花板,它应该没问题),然后可以用作索引。

如果您借用的代码是为Python 3编写的,那么{3}}的Python 3版本确实会返回一个int。 1,2 所以它在Python 3中有用,但是你的后端是Python 2没有。

(这就提出了为什么你要将代码反向移植到Python 2而不仅仅是使用Python 3的问题,但是......也许你有理由这样做。)

<子> 1。实际上,它仅在int上调用时返回float。当调用其他类型时,保证返回匹配Integral的内容,但这并不一定意味着它可用作索引。但这很少会出现问题,而且不在这里。

<子> 2。 Python 2旨在返回C专家期望的类型; Python 3旨在返回任何令人困惑或最有用的内容。最着名的例子是5/2在2.x中为2,在3.x中为2.5。

答案 1 :(得分:0)

您收到此错误是因为您需要传递int而不是float。 How to build a DLL from the command line in Windows using MSVC函数返回一个浮点数。您可能希望将其类型化为整数。