0

Let's say I want to iterate over a numpy array and print each item. I'm going to use this later on to manipulate the (i,j) entry in my array depending on some rules.

I've read the numpy docs and it seems like you can access individual elements in an array easily enough using similar indexing(or slicing) to lists. But it seems that I am unable to do anything with each (i,j) entry when I try to access it in a loop.

row= 3
column = 2
space = np.random.randint(2, size=(row, column))
print space, "\n"

print space[0,1]
print space[1,0]   #test if I can access indiivdual elements

output:

[[1,1
 [1,1
 [0,0]]

1
1

for example, using the above I want to iterate over every row and column and print each entry. I would think to use something like the following:

for i in space[0:row,:]:
    for j in space[:,0:column]:
        print space[i,j]

the output I get is

[1,1]
[1,1]
[1,1]
[1,1]
[1,1]
[1,1]
[1,1]
[1,1]
[1,1]

Obviously this does not work. I believe the problem is that I'm accessing entire rows and columns instead of elements within any given row and column. I've been going over the numpy docs for a couple of hours and I am still unsure of how to go about this.

My main concern is I want to change each (i,j) entry by using a loop and some conditionals, for example (using the above loop):

for i in space[0:row,:]:
    for j in space[:,0:column]:
         if [i+1,j] + [i,j+1] == 2:
             [i,j] = 1
3
  • 1
    i and j are indices. You need to iterate i in range(row) and j in range(column). Then you can set space[i, j] to whatever you want. Commented Oct 8, 2016 at 23:15
  • 1
    I should add that using loops for simple tasks defeats the purpose of using numpy, because you will lose any speed benefit that numpy provides. Learn about numpy indexing, which allows you to assign to multiple locations using lists of indices, and which will be much faster than using loops Commented Oct 8, 2016 at 23:18
  • I have been reading that page for a while now. I haven't been able to make the connection on how to do that. Under which heading should I look on that link? Or maybe if you could provide an example of how to do something like that it would illuminate a lot for me. Thanks! Commented Oct 8, 2016 at 23:22

2 Answers 2

2

Start with:

for i in range(row):
    for j in range(column):
        print space[i,j]

You are generating indices in your loops which index some element then!

The relevant numpy docs on indexing are here.

But it looks, that you should also read up basic python-loops.

Start simple and read some docs and tutorials. After i saw Praveen's comment, i felt a bit bad with this simple answer here which does not offer much more than his comment, but maybe the links above are just what you need.

A general remark on learning numpy by trying:

  • regularly use arr.shape to check the dimensions
  • regularly use arr.dtype to check the data-type

So in your case the following should have given you a warning (not a python one; one in your head) as you probably expected i to iterate over values of one dimension:

print((space[0:row,:]).shape)
# output: (3, 2)
Sign up to request clarification or add additional context in comments.

1 Comment

Both yours and Praveen's comments fixed the issue. I honestly thought it would have to be something more complicated for numpy arrays. But apparently not!
1

There are many ways of iterating over a 2d array:

In [802]: x=np.array([[1,1],[1,0],[0,1]])
In [803]: print(x)    # non-iteration
[[1 1]
 [1 0]
 [0 1]]

by rows:

In [805]: for row in x:
     ...:     print(row)
[1 1]
[1 0]
[0 1]

add enumerate to get an index as well

In [806]: for i, row in enumerate(x):
     ...:     row += i

In [807]: x
Out[807]: 
array([[1, 1],
       [2, 1],
       [2, 3]])

double level iteration:

In [808]: for i, row in enumerate(x):
     ...:     for j, v in enumerate(row):
     ...:         print(i,j,v)         
0 0 1
0 1 1
1 0 2
1 1 1
2 0 2
2 1 3

of course you could iterate on ranges:

for i in range(x.shape[0]):
    for j in range(x.shape[1]):
         x[i,j]...

for i,j in np.ndindex(x.shape):
    print(i,j,x[i,j])

Which is best depends, in part, on whether you need to just use the values, or need to modify them. If modifying you need an understanding of whether the item is mutable or not.

But note that I can remove the +1 without explicit iteration:

In [814]: x-np.arange(3)[:,None]
Out[814]: 
array([[1, 1],
       [1, 0],
       [0, 1]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.