【问题标题】:Python error " 'float' object cannot be interpreted as an index" in Canopy environmentCanopy 环境中的 Python 错误“'float' 对象不能被解释为索引”
【发布时间】: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 编写的。

标签: python numpy canopy


【解决方案1】:

你说:

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

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

返回 x 的上限作为浮点数,大​​于或等于 x 的最小整数值。

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


如果您借用的代码是为 Python 3 编写的,那么 Python 3 版本的 math.ceil 确实会返回一个 int。1,2 所以它在 Python 3 中工作,但您向后移植到 Python 2没有。

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


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

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

【讨论】:

  • 我把 math.ceil 改成了 "int" 并且成功了,谢谢你的回答!
【解决方案2】:

您收到此错误是因为您需要传递一个 int 而不是 float。 ciel 函数返回一个浮点数。您可能希望将其类型转换为整数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-11
    • 2018-05-14
    • 2015-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多