3

This may be a well-known question stored in some FAQ but i can't google the solution. I'm trying to write a scalar function of scalar argument but allowing for ndarray argument. The function should check its argument for domain correctness because domain violation may cause an exception. This example demonstrates what I tried to do:

import numpy as np
def f(x):
    x = np.asarray(x)
    y = np.zeros_like(x)
    y[x>0.0] = 1.0/x
    return y

print f(1.0)

On assigning y[x>0.0]=... python says 0-d arrays can't be indexed. What's the right way to solve this execution?

4
  • 1
    Tricky ;). Use y[np.asarray(x>0.0)] = ... should do the trick. Commented Sep 1, 2013 at 17:46
  • Thanks you seberg! I don't knw why but it works! Commented Sep 1, 2013 at 17:52
  • 1
    Comes down to difference between scalar arrays and (array-)scalars... And boolean indexing is only triggered with boolean arrays at this time at least. Commented Sep 1, 2013 at 17:59
  • @seberg please consider posting your suggestion as an answer Commented Jan 30, 2014 at 23:51

2 Answers 2

2

This will work fine in NumPy >= 1.9 (not released as of writing this). On previous versions you can work around by an extra np.asarray call:

x[np.asarray(x > 0)] = 0
Sign up to request clarification or add additional context in comments.

Comments

1

Could you call f([1.0]) instead?

Otherwise you can do:

x = np.asarray(x)
if x.ndim == 0:
    x = x[..., None]

1 Comment

Not me call it but scipy.integration.quad does. Anyway, seberg gave the trick.

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.