Search code examples
pythonarraysnumpymultidimensional-arrayiterator

Iterating through the rows of a multidimensional array within a function Python


Is there a way I could run multi in the result code down below so that it gives the expected output below where the iterations of a,b,c listed below. I tried to make it so that the [:,] could be used to iterate through the rows in the 2 dimensional array but it does not work. How could I iterate all the rows to get the expected output below without a for loop. The for loop and the numpy code are meant to the same thing.

Numpy Code:

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 loop Code:

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)

Result:

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

Solution

  • Full display from creating your array

    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)
    

    This is a 1d array, not 2d.

    Making an array, as opposed to just the list, [a,b,c] does nothing useful.

    Just apply your calculation to each array:

    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.])]
    

    Usually when you have arrays (or lists) that differ in length, there's little you can do to perform the actions as though you had a 2d array.