在Python函数中遍历多维数组的行



是否有一种方法可以在下面的result代码中运行multi,以便它给出下面列出的a,b,c迭代的预期输出。我试图使[:,]可以用来迭代二维数组中的行,但它不起作用。在没有for循环的情况下,我如何迭代所有行以获得下面的预期输出?for循环和numpy代码的意思是一样的。

Numpy代码:

import numpy as np
a = np.array([1,2,3,11,23])
b = np.array([-2, 65, 8, 0.98])
c = np.array([5, -6])
multi = np.array([a, b, c])
result = (multi[:,] > 0).cumsum() / np.arange(1, len(multi[:,])+1) * 100
For循环代码:

import numpy as np
a = np.array([1,2,3,11,23])
b = np.array([-2, 65, 8, 0.98])
c = np.array([5, -6])
multi = np.array([a, b, c])
for i in range(len(multi)):
predictability = (multi[i] > 0).cumsum() / np.arange(1, len(multi[i])+1) * 100
print(predictability)

结果:

[[100. 100. 100. 100. 100.],
[ 0.         50.         66.66666667 75.        ],
[100.  50.]]

从创建数组开始全面显示

In [150]: np.array([1,100,200],str)
Out[150]: array(['1', '100', '200'], dtype='<U3')
In [151]: np.array([1,100,200.],str)
Out[151]: array(['1', '100', '200.0'], dtype='<U5')
In [152]: a = np.array([1,2,3,11,23])
...: b = np.array([-2, 65, 8, 0.98])
...: c = np.array([5, -6])
...: multi = np.array([a, b, c])
<ipython-input-152-d6f4f1c3f527>:4: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
multi = np.array([a, b, c])
In [153]: multi
Out[153]: 
array([array([ 1,  2,  3, 11, 23]), array([-2.  , 65.  ,  8.  ,  0.98]),
array([ 5, -6])], dtype=object)

这是一个一维数组,不是二维数组。

制作一个数组,而不是列表中,[a,b,c]没有有用。

只需将您的计算应用到每个数组:

In [154]: [(row > 0).cumsum() / np.arange(1, len(row)+1) * 100 for row in [a,b,c]]
Out[154]: 
[array([100., 100., 100., 100., 100.]),
array([ 0.        , 50.        , 66.66666667, 75.        ]),
array([100.,  50.])]

通常当你有长度不同的数组(或列表)时,你几乎不能像有一个2d数组那样执行操作。

最新更新