【问题标题】:ValueError: too many boolean indices for a n=600 array (float)ValueError:n = 600 数组的布尔索引过多(浮点数)
【发布时间】:2015-01-02 21:39:18
【问题描述】:

我在尝试运行时遇到问题(在 Python 上):

#Loading in the text file in need of analysis
x,y=loadtxt('2.8k to 293k 15102014_rerun 47_0K.txt',skiprows=1,unpack=True,dtype=float,delimiter=",")

C=-1.0      #Need to flip my voltage axis

yone=C*y    #Actually flipping the array

plot(x,yone)#Test

origin=600.0#Where is the origin? i.e V=0, taking the 0 to 1V elements of array

xorg=x[origin:1201]# Array from the origin to the final point (n)

xfit=xorg[(x>0.85)==True] # Taking the array from the origin and shortening it further to get relevant area

它返回 ValueError。我尝试用一​​个包含 10 个元素的小得多的数组来完成这个过程,xfit=xorg[(x>0.85)==True] 命令工作正常。该程序试图做的是将某些数据的视野缩小到相关点,以便我可以拟合一条最适合数据线性元素的线。

对于格式混乱,我深表歉意,但这是我在此网站上提出的第一个问题,因为我无法搜索我能理解的问题所在。

【问题讨论】:

  • (x>0.85)==True 最好写成x>0.85
  • xorg 有 600 个元素,x 至少有 1200 个元素。当您使用表达式 x<0.85 索引 xorg 时,您正在使用一个至少包含 1200 个元素的布尔数组来索引一个 600 个元素的数组。 python大声抱怨...

标签: python arrays numpy boolean


【解决方案1】:

此答案适用于不了解 numpy 数组的人(如我),感谢 MrE 提供指向 numpy 文档的指针。

Numpy 数组具有布尔掩码这个不错的特性。

对于 numpy 数组,大多数运算符会返回应用于每个元素的操作数组 - 而不是像普通 Python 列表那样的单个结果:

>>> alist = range(10)
>>> alist
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> alist > 5
True

>>> anarray = np.array(alist)
>>> anarray
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

>>> anarray > 5
array([False, False, False, False, False, False,  True,  True,  True,  True], dtype=bool)

您可以使用 bool 数组作为 numpy 数组的索引,在这种情况下,您将获得一个过滤后的数组,用于对应的 bool 数组元素为 True 的位置。

>>> mask = anarray > 5
>>> anarray[mask]
array([6, 7, 8, 9])

掩码不能大于数组:

>>> anotherarray = anarray[mask]
>>> anotherarray
array([6, 7, 8, 9])

>>> anotherarray[mask]
ValueError: too many boolean indices

所以你不能使用比你要屏蔽的数组更大的掩码:

>>> anotherarray[anarray > 7]
ValueError: too many boolean indices

>>> anotherarray[anotherarray > 7]
array([8, 9])

由于xorg 小于x,基于x 的掩码将比xorg 长,您会得到ValueError 异常。

【讨论】:

    【解决方案2】:

    尝试以下方法: 替换你的代码

    xorg=x[origin:1201]
    xfit=xorg[(x>0.85)==True]    
    

    mask = x > 0.85
    xfit = xorg[mask[origin:1201]]
    

    这在 x 是 numpy.ndarray 时有效,否则您可能会遇到问题,因为高级索引将返回视图,而不是副本,请参阅 SciPy/NumPy documentation

    我不确定你是否喜欢使用 numpy,但是在尝试拟合数据时,无论如何,numpy/scipy 是一个不错的选择...

    【讨论】:

    • 我明白了!这现在有效,但我很好奇为什么原始代码不起作用。把我当作 python-noob 对待,因为我几乎是。到目前为止非常感谢。
    • 抱歉,我忘记链接有关高级索引的文档。我会在答案中添加它。正如@Mr E 所说,只有 numpy 数组才能在这种索引下正常工作,对于 python 列表,只返回视图而不是副本。这意味着您可能会在迭代会话中看到它,但您的 xint 数组不会改变。
    【解决方案3】:

    改变

    xfit=xorg[x>0.85]
    

    xfit=xorg[xorg>0.85]
    

    xxorg 大,所以 x > 0.85 的元素比 xorg

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-18
    • 2020-03-25
    • 2018-04-01
    • 2017-11-17
    • 1970-01-01
    • 2019-11-04
    • 1970-01-01
    • 2016-02-19
    相关资源
    最近更新 更多