在函数内迭代多维数组的行 Python

Iterating through the rows of a multidimensional array within a function 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.])]

通常,当您拥有长度不同的数组(或列表)时,您几乎无法像拥有二维数组那样执行操作。