1

I can get the index of non-zero numpy arrays as follows:

a = np.array([0., 1., 0., 2.])
i = np.nonzero(a)

This returns (array([1, 3]),). I can get the corresponding values as:

v = a[i]

Now what I would like to do is create a list with each of the (index, value) tuples. I guess one way to do so is to write a for loop as follows;

l = list()
for x in range(0, len(v)):
    l.append((i[0][x], v[x]))

However, I was wondering if there is a better way to do this without writing the loop.

2
  • What is index in index[0][x]? Commented Jul 22, 2015 at 14:18
  • Sorry, that was a type from me. I was doing something in ipython and messed up the variable names during copying. Thanks for pointing it out. Apologies. Commented Jul 22, 2015 at 14:19

3 Answers 3

2

If you really want tuples, you can get them with:

indexes= np.where(a!=0)[0]   #or np.nonzero(a)[0]
values=a[indexes]
zip(values, indexes)         #or list(zip(values, indexes)) in python 3, if you need to access more than once
Sign up to request clarification or add additional context in comments.

Comments

1

You could use a list comprehension

l = [(x, v[x]) for x in i[0]]

or use zip as the other answers suggest

3 Comments

this is somewhat slower than zip, but it's arguably more readable. The order inside the tuple is swapped compared to the example
I do not think the order is swapped. Here v is iterating over the indexes. I think the confusion is due to the fact that v is something different here than my original example.
Sorry for that, I changed the variable names to better reflect the original usage in the OP.
0

I am not sure if numpy has a library to do that, but you can do this using zip() function. Example -

>>> i = [1,2,3,4]
>>> v = [5,6,7,8]
>>> list(zip(i,v))
[(1, 5), (2, 6), (3, 7), (4, 8)]

You do not need list() for Python 2.x , as zip returns a list of tuples in Python 2.x .

For your case, you can try

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.