Home > other >  How to slice a 1-dimensional ndarray of tuples
How to slice a 1-dimensional ndarray of tuples

Time:04-10

Give a 1-dimensional numpy ndarray as seen in the image below: enter image description here

The shape is: (9,) The class type is: <class 'numpy.ndarray'>

How do I slice this data structure so as to get the 3rd and 4th columns (using the term columns loosely) as seen in this image:

enter image description here

Note that I could have used a conversion to pandas dataframe to handle this but my core question is how can I slice this using numpy or any inbuilt python slicing function?

CodePudding user response:

you can try this

sliced = [l[2:4] for l in my_list]

CodePudding user response:

If the shape is (9,), you can reshape it first then slice to get your desired columns. As a simple example

import numpy as np

a = np.array([[3, 4, 5], [9, 7, 5]])
b = a.reshape((6,))
c = b.reshape(2, 3)
d = c[:, [1,2]]

print(a)
print(b)
print(c)
print(d)

Output

[[3 4 5]
 [9 7 5]]
[3 4 5 9 7 5]
[[3 4 5]
 [9 7 5]]
[[4 5]
 [7 5]]
  • Related