值错误:n=600数组的布尔索引太多(浮点)

2024-09-28 23:54:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我在尝试运行(在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]命令可以正常工作。这个程序要做的是缩小一些数据的视野,缩小到一个相关点,这样我就可以拟合出一条最适合数据线性元素的直线。在

我很抱歉格式混乱,但这是我在这个网站上问的第一个问题,因为我无法搜索到我能理解我哪里出错了。在


Tags: oftheto数据textinfromtrue
3条回答

这个答案是为那些不知道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的位置。在

^{pr2}$

掩码不能大于数组:

>>> 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])

由于xorgx小,基于x的掩码将比xorg长,并得到ValueError异常。在

尝试以下操作: 替换您的代码

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

^{pr2}$

当x是a时,这是有效的努比·恩达雷,否则您可能会遇到问题,因为高级索引将返回一个视图,而不是一个副本,请参见SciPy/NumPy documentation。在

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

改变

xfit=xorg[x>0.85]

^{pr2}$

xxorg大,因此x > 0.85的元素比xorg

相关问题 更多 >