为什么此代码无法正常工作?我不能让这个numpy数组正确调整大小。Python NumPy无法正确调整大小
import numpy
a = numpy.zeros((10,10))
a[3,2] = 8
a.resize((5,5))
if a[3,2] == 8:
print "yay"
else:
print "not working"
raw_input()
为什么此代码无法正常工作?我不能让这个numpy数组正确调整大小。Python NumPy无法正确调整大小
import numpy
a = numpy.zeros((10,10))
a[3,2] = 8
a.resize((5,5))
if a[3,2] == 8:
print "yay"
else:
print "not working"
raw_input()
从文档[help(a.resize)
]:
Shrinking an array: array is flattened (in the order that the data are
stored in memory), resized, and reshaped:
>>> a = np.array([[0, 1], [2, 3]], order='C')
>>> a.resize((2, 1))
>>> a
array([[0],
[1]])
在你的情况,[3,2]
被当作为一个扁平的数据列表考虑存储在索引32:
>>> a = numpy.zeros((10,10))
>>> a[3,2] = 8
>>> list(a.flat).index(8)
32
32> = 25,所以你的改变不会在重新调整。如果你只是想只保留了几个值的,那么你可以使用
>>> a = a[:5, :5]
>>> a
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 8., 0., 0.],
[ 0., 0., 0., 0., 0.]])
>>> a[3,2]
8.0
,或者如果你真的愿意,你可以通过调整大小前拷贝数据:
>>> a = numpy.zeros((10,10))
>>> a[3,2] = 8
>>> a.flat[:(5*5)] = a[:5, :5].flat
>>> a.resize((5,5))
>>> a[3,2]
8.0
,但我不不太明白这一点。 [我不记得调整大小如何处理内存,但我不会担心。]
从文档,http://docs.scipy.org/doc/numpy/reference/generated/numpy.resize.html
numpy.resize(一,new_shape)
返回具有指定形状的新阵列。
如果新数组大于原始数组,则新数组填充a的重复副本。请注意,此行为不同于a.resize(new_shape),它使用零填充而不是a的重复副本。
对于你希望你需要手动复制你想要的新阵列,以保持价值观的行为,像
a=a[:5,:5]
你期望发生的,什么是真正发生什么? –