循环 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 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)
Consider the following convenient looping idiom.
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
This gives
shape of
[['a' 'b']
['c' 'd']]
is (2, 2)
shape of ['a' 'b'] is (2,)
shape of ['c' 'd'] is (2,)
My question is, can one preserve the convenient for row in x
idiom while returning arrays which have shape (2,1), in this case? Thanks.
A function which converts the shape of the subarray from (2,) to (2,0) would be fine. E.g.
for row in x:
print "shape of", somefunc(row), "is", row.shape
returning
shape of ['a' 'b'] is (2,1)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不明白为什么你会想要这样,但你可以尝试一下:
在我看来,一维数组更容易处理。因此,将其重塑为“一维矩阵”对我来说没有多大意义。
I don't see why you would want that but you could give this a try:
In my optinion, a 1d-array is easier to handle. So it does not make much sense to me to reshape it to a "1d-matrix".
您可以使用
numpy.expand_dim
增加任意 numpy 数组的排名:You can use
numpy.expand_dim
to increase the rank of any numpy array: