1

First I have a scalar time series stored in a numpy array:

ts = np.arange(10) 

which is

array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) 

Suppose I want to extract from ts a series of vectors (2,1,0), (3,2,1), (4,3,2), etc., I can think of the following code to do it:

for i in range(len(ts)-2): print(ts[2+i:i-1:-1]) 

However, when i=0, the above code returns an empty array rather than [2,1,0] because the loop body will become

print(ts[2:-1:-1]) 

where the -1 in the middle creates trouble.

My question is: is there a way to make the indexing work for [2,1,0]?

3 Answers 3

3

You need use None:

ts = np.arange(10) for i in range(len(ts)-2): print(ts[2+i:None if i == 0 else i - 1:-1]) 
Sign up to request clarification or add additional context in comments.

3 Comments

Nice! didn't know I can put a if...else there
not directly related to the question, this does not work in Cython
wdg, the if-else-construct is for using it inline
3

This should work too:

print(ts[i:i+3][::-1]) 

Comments

0

another way is to do the following

slices = np.arange(3) result = np.array([]) while slices[2] < len(ts): # print(ts[slices]) result = np.r_[result , ts[slices]] slices += 1 result.reshape((-1 , 3)) Out[165]: array([[ 0., 1., 2.], [ 1., 2., 3.], [ 2., 3., 4.], [ 3., 4., 5.], [ 4., 5., 6.], [ 5., 6., 7.], [ 6., 7., 8.], [ 7., 8., 9.]]) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.