Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to index 0-d array in Python?

Tags:

python

numpy

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?

like image 626
Evgeny P. Kurbatov Avatar asked Jul 11 '26 01:07

Evgeny P. Kurbatov


1 Answers

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
like image 63
seberg Avatar answered Jul 13 '26 15:07

seberg



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!