0

if i have an array

a = np.array([[1,2,3],[4,5,6],[7,8,9]])

output would be a =[1,2,3],[4,5,6],[7,8,9]

using slice [start:endindex:stepindex], how could i retrieve 3 and 7?

is it possible?

I have tried

a[:3:2]

this gave me 1rst row and third row

1 Answer 1

1
In [928]: a = np.array([[1,2,3],[4,5,6],[7,8,9]])                                                      
In [929]: a                                                                                            
Out[929]: 
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

[3,7] isn't regular pattern in this 2d array. But its flattened view:

In [931]: a.ravel()                                                                                    
Out[931]: array([1, 2, 3, 4, 5, 6, 7, 8, 9])
In [932]: a.ravel()[2::4]                                                                              
Out[932]: array([3, 7])
In [933]: a.flat[2::4]                                                                                 
Out[933]: array([3, 7])

Now guarantee that it can be extended for larger arrays and selections.

Sign up to request clarification or add additional context in comments.

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.