0
>>> s = {0, 4, 27}
>>> a = numpy.arange(10)
>>> t = some_func(a)
>>> t
[1, 0, 0, 0, 1, 0, 0, 0, 0, 0]

What's the canonical some_func needed to be to make this work?

What I've tried

I've tried vectorizing a lambda function, which works ... it just doesn't feel like the right way to do this.

>>> f = lambda i: i in s
>>> vf = numpy.vectorize(f)
>>> t = numpy.fromfunction(vf, a.shape)
>>> t.astype(int)
array([1, 0, 0, 0, 1, 0, 0, 0, 0, 0])
2
  • I think what you want is in1d from numpy. docs.scipy.org/doc/numpy/reference/generated/… Commented Apr 7, 2014 at 9:27
  • Dont' really do numpy, but would something like [i in s for i in a] work here? Commented Apr 7, 2014 at 9:29

2 Answers 2

3

Use in1d with s as a NumPy array

>>> import numpy as np
>>> s = np.array([0, 4, 27])
>>> a = np.arange(10)
>>> t = np.in1d(a, s)
>>> t
array([ True, False, False, False,  True, False, False, False, False, False], dtype=bool)
>>> 
Sign up to request clarification or add additional context in comments.

Comments

0

This would be faster:

t = np.zeros(10, int)
sa = np.array(list(s))
t[sa[sa<10]] = 1

Unless of course, a is not np.arange()

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.