我最近在使用结构化numpy数组时看到了一种现象,这种现象没有任何意义。我希望有人能帮助我理解正在发生的事情。我提供了一个最小的工作示例来说明问题。问题是这样的:为什么对布尔索引结构化数组的赋值依赖于索引排序?
当索引用布尔面具结构化numpy的数组,这个工程:
arr['fieldName'][boolMask] += val
但以下不会:
arr[boolMask]['fieldName'] += val
这里是一个最小的工作示例:
import numpy as np
myDtype = np.dtype([('t','<f8'),('p','<f8',(3,)),('v','<f4',(3,))])
nominalArray = np.zeros((10,),dtype=myDtype)
nominalArray['t'] = np.arange(10.)
# In real life, the other fields would also be populated
print "original times: {0}".format(nominalArray['t'])
# Add 10 to all times greater than 5
timeGreaterThan5 = nominalArray['t'] > 5
nominalArray['t'][timeGreaterThan5] += 10.
print "times after first operation: {0}".format(nominalArray['t'])
# Return those times to their original values
nominalArray[timeGreaterThan5]['t'] -= 10.
print "times after second operation: {0}".format(nominalArray['t'])
运行此产生以下输出:
original times: [ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
times after first operation: [ 0. 1. 2. 3. 4. 5. 16. 17. 18. 19.]
times after second operation: [ 0. 1. 2. 3. 4. 5. 16. 17. 18. 19.]
我们在此清楚地看到第二个操作没有效果。如果有人可以解释为什么会发生这种情况,将不胜感激。
它不会是'nominalArray [“t”] [timeGreaterThan5] - = 10' –
@PadraicCunningham这将解决问题。我只是想知道为什么这是解决方案。这里的排序有什么特别之处? – tintedFrantic
我现在得到你,他们都返回不同的对象,一个是视图,另一个不是,我想像高级与普通索引,'nominalArray [timeGreaterThan5]'返回'[(16.0,[0.0,0.0,0.0],[ 0.0,0.0,0.0])...'所以从'nominalArray [timeGreaterThan5]'返回的片不是查看对象 –