gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:48:13 26 4
gpt4 key购买 nike

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

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)

最佳答案

您可以使用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)

关于python - 循环 numpy 数组时返回具有相同维度的子数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8062826/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com