0

The use case is that of rules can be turned on or off. Was wondering if I could use the numpy array indexing expression for this. For e.g. user can specify:

10:40:3

which would mean rules are active within day 10 to 40 every third day. How do I index in an array using such given expression.

2
  • What are the elements of the array? Commented Feb 12, 2017 at 20:11
  • Should it matter? I guess could be integers. Commented Feb 12, 2017 at 20:14

1 Answer 1

3

A 10:40:3 expression only works inside of a [], e.g.

x[10:40:3]

where x is a list or array.

The Python interpreter translates that into:

x.__getitem__(slice(10,40,3))

It would be possible to convert a '10:40:3' string into a slice(10,40,3) object, but you could also accept three integers and build the slice from that.

A slice can be used as:

idx = slice(10,40,3)
x[idx]

In [683]: idx = slice(1,10,2)
In [684]: np.arange(20)[idx]
Out[684]: array([1, 3, 5, 7, 9])
In [685]: np.arange(1,10,2)
Out[685]: array([1, 3, 5, 7, 9])

simple way of making a slice from the string:

In [687]: slice(*[int(i) for i in astr.split(':')])
Out[687]: slice(1, 10, 2)

numpy has also defined some special object that can help with slices, but none work with strings

In [690]: np.r_[idx]
Out[690]: array([1, 3, 5, 7, 9])
In [691]: np.s_[1:10:2]
Out[691]: slice(1, 10, 2)
In [693]: np.s_[1::2]
Out[693]: slice(1, None, 2)
In [694]: np.s_[:]
Out[694]: slice(None, None, None)
Sign up to request clarification or add additional context in comments.

1 Comment

Nice! Didn't knew (or thought) that index was itself an object. It is designed well. Thanks.

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.