Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over numpy array rows in python

I am trying to iterate over the rows of two numpy arrays in python, using the following for loop:

for i, j in range(X.shape[0]), range(y.shape[0]):

But I am getting the following error:

ValueError: too many values to unpack (expected 2)

I thought that by creating lists with the number of rows in each array I could iterate over X using the value of i, and over y using the value of j.

Could somebody please explain why this is not working, and how I could make it work instead? Thanks!

like image 631
user9654649 Avatar asked May 19 '26 02:05

user9654649


1 Answers

This is not what you are looking to do.

To iterate over rows in X and rows in Y, you should use nested loops:

for i in range(X.shape[0]):
    for j in range(Y.shape[0]):
        func(i, j)

Having said this, I would strongly advise you use loops as a last resort. Try to vectorise functions where possible.

If you must loop, you may be able to improve performance by using numba.

like image 138
jpp Avatar answered May 21 '26 15:05

jpp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!