gpt4 book ai didi

python - 切片 2d numpy 数组

转载 作者:行者123 更新时间:2023-12-01 06:13:10 24 4
gpt4 key购买 nike

以下代码:

import numpy as p
myarr=[[0,1],[0,6],[0,1],[0,6],[0,1],[0,6],[0,1],[0,6],[0,1],[0,6],[0,1],[0,6],[0,1],[0,6],[0,1],[0,6],[0,1],[0,6]]
copy=p.array(myarr)
p.mean(copy)[:,1]

正在生成以下错误消息:

Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
p.mean(copy)[:,1]
IndexError: 0-d arrays can only use a single () or a list of newaxes (and a single ...) as an index

我查了一下语法 at this link我似乎正在使用正确的语法来切片。但是,当我输入

copy[:,1]

进入Python shell,它给出了以下输出,这显然是错误的,并且可能是抛出错误的原因:

array([1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6, 1, 6])

谁能告诉我如何修复我的代码,以便我可以提取第二列,然后按照上面原始代码中的预期取第二列的平均值?

编辑:

感谢您的解决方案。然而,我的帖子过于简单化了我的实际问题。我在实际代码中使用了您的解决方案,但出现了新错误。这是我尝试过的您的解决方案之一的真实代码:

    filteredSignalArray=p.array(filteredSignalArray)

logical=p.logical_and(EndTime-10.0<=matchingTimeArray,matchingTimeArray<=EndTime)
finalStageTime=matchingTimeArray.compress(logical)
finalStageFiltered=filteredSignalArray.compress(logical)

for j in range(len(finalStageTime)):
if j == 0:
outputArray=[[finalStageTime[j],finalStageFiltered[j]]]
else:
outputArray+=[[finalStageTime[j],finalStageFiltered[j]]]

print 'outputArray[:,1].mean() is: ',outputArray[:,1].mean()

这是新代码现在生成的错误消息:

File "mypath\myscript.py", line 1545, in WriteToOutput10SecondsBeforeTimeMarker
print 'outputArray[:,1].mean() is: ',outputArray[:,1].mean()
TypeError: list indices must be integers, not tuple

第二次编辑:

现在我添加了这个问题已解决:

    outputArray=p.array(outputArray)

在我的代码上方。

我已经工作了太多时间,如果犯了这些错误,需要休息一段时间。

最佳答案

您可能指的是 p.mean(copy[:,1]) 以及 mean() 函数调用之前的索引。我没有看到 copy 的内容有问题 - 它看起来对我来说是正确的。

关于python - 切片 2d numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4664502/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com