循环 numpy 数组时返回具有相同维度的子数组

发布于 2024-12-14 17:43:30 字数 615 浏览 0 评论 0原文

考虑以下方便的循环习惯用法。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

迷鸟归林 2024-12-21 17:43:33

我不明白为什么你会想要这样,但你可以尝试一下:

for row in x:
    print "shape of", row, "is", numpy.reshape(row, (1, row.size)).shape

在我看来,一维数组更容易处理。因此,将其重塑为“一维矩阵”对我来说没有多大意义。

I don't see why you would want that but you could give this a try:

for row in x:
    print "shape of", row, "is", numpy.reshape(row, (1, row.size)).shape

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".

剧终人散尽 2024-12-21 17:43:32

您可以使用 numpy.expand_dim 增加任意 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)

You can use numpy.expand_dim to increase the rank of any numpy array:

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文