Python 在numpy数组上循环时返回具有相同维度的子数组
考虑以下方便的循环习惯用法Python 在numpy数组上循环时返回具有相同维度的子数组,python,arrays,numpy,Python,Arrays,Numpy,考虑以下方便的循环习惯用法 import numpy print "shape of" x = numpy.array([['a', 'b'], ['c', 'd']]) print x print "is", x.shape for row in x: print "shape of", row, "is", row.shape 这给 shape of [['a' 'b'] ['c' 'd']] is (2, 2) shape of ['a' 'b'] is (2,) shape
import numpy
print "shape of"
x = numpy.array([['a', 'b'], ['c', 'd']])
print x
print "is", x.shape
for row in x:
print "shape of", row, "is", row.shape
这给
shape of
[['a' 'b']
['c' 'd']]
is (2, 2)
shape of ['a' 'b'] is (2,)
shape of ['c' 'd'] is (2,)
我的问题是,在这种情况下,在返回具有形状(2,1)的数组时,是否可以保留方便的for row in x
习惯用法?谢谢
将子阵列的形状从(2,)转换为(2,0)的函数就可以了。例如
for row in x:
print "shape of", somefunc(row), "is", row.shape
返回
shape of ['a' 'b'] is (2,1)
我不明白你为什么想要这样,但你可以试试:
for row in x:
print "shape of", row, "is", numpy.reshape(row, (1, row.size)).shape
在我的optinion中,一维数组更容易处理。因此,将其重塑为“1d矩阵”对我来说没有多大意义。您可以使用它来增加任何numpy数组的秩:
In [7]: x=np.array([1,2,3,4])
In [8]: x.shape
Out[8]: (4,)
In [9]: np.expand_dims(x,axis=-1).shape
Out[9]: (4, 1)
@沃尔坦:对,编辑。谢谢。谢谢,但我想你是想写
(row.size,1)
@FaheemMitha,因为['a''b']
是一个行向量,它应该是(1,元素数)
。你说得对。顺便说一句,我有一个需要2d数组的函数,所以我别无选择,只能更改维度。这是一个很好的解决方案。一般来说,它与重塑
相比如何?@FaheemMitha由于扩展_dims
和重塑
都不会将数组复制到内存中的新位置,因此这两种方法实际上是等效的。所以,这取决于你喜欢哪一种口味。@Woltan:重塑
不是更一般吗?@FaheemMitha你说一般是什么意思?这两个函数都是numpy
库的有效函数。这是一个品味的问题,你手头有什么样的参数,你想用哪一个。我自己经常使用重塑
。在你的情况下,我建议使用expand_dims
,因为你不需要知道数组的大小…@Woltan:一般来说,我的意思是一个比另一个更适用。一般的意思。至于使用重塑
,人们总是可以像你一样使用.size
,所以我看不出有什么问题。