0

you all! I have very specific question about np.nonzero and it's function while slicing a np.array (First of all, I am not 100% sure it is called slicing). I found a Python script on the internet and get an error at the following line:

if (i in dividendsStep):
   div = dividends[1][np.nonzero(dividendsStep == (i))[0]]
   currentDividend = currentDividend + div

And I get the following error:

div = dividends[1][np.nonzero(dividendsStep == (i))[0]]
TypeError: only integer scalar arrays can be converted to a scalar index

When I drop np.nonzero(x), it doesn't generate the error but it does not generate the right answer (I know the input variables and what the answer should be).

When I print the np.nonzero part, I get the following output:

print(np.nonzero(dividendsStep==(i)))
(array([0], dtype=int32),)

When I print dividends, I get the following output

print(dividends)
[[0.2917], [2.06]]

Furthermore I think it is a python 2 script (I had to replace xrange for range). I don't know if it's relevant when I try the same code in a Python 2.7 interpreter I get the same error.

Question

What is the function of np.nonzero in the slicing? I know it returns the indices of the elements that are non-zero but it doesn't make sense in this 'slice'. If it is called different, please let me know, I will update it right away!

Answer

Ubuntu has provided the answer:

dividends=np.array(dividends)
4
  • What kind of object is dividends[1]? If type(dividends[1]) returns list, then see TypeError when trying to use list of integers in numpy array. Commented Jul 13, 2019 at 17:27
  • @unutbu if I print type, I get the following error: TypeError: 'str' object is not callable. When I print(dividends), I got two lists in a list. I will take a look at your suggestion. Thanks in advance! Commented Jul 13, 2019 at 17:31
  • @unutbu I also updated the question, so you can see the printout Commented Jul 13, 2019 at 17:33
  • nonzero gives a tuple of arrays. Here it is 1 array which [0] extracts. Looks like dividends is a list of lists. Lists can only be indexed with an integer, or something that can turned into one. Commented Jul 13, 2019 at 20:03

0

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.