Nisarg Dave
Nisarg Dave

Reputation: 103

Numpy python array slicing

I have an array as shown below,

[[240.66666667 171.22222222 158.33333333]
 [218.66666667 134.77777778 143.33333333]
 [197.33333333 118.55555556 128.44444444]
 [195.22222222 119.33333333 126.11111111]
 [196.77777778 118.55555556 123.77777778]
 [183.11111111 111.88888889 118.88888889]
 [173.77777778 106.77777778 114.44444444]]

I want to slice the first and third columns for all the rows and wanna get this output,

[[240.66666667 158.33333333]
 [218.66666667 143.33333333]
 [197.33333333 128.44444444]
 [195.22222222 126.11111111]
 [196.77777778 123.77777778]
 [183.11111111 118.88888889]
 [173.77777778 114.44444444]]

Does anyone have any ideas?

Output screenshot:

enter image description here

Upvotes: 3

Views: 88

Answers (2)

miador
miador

Reputation: 368

You can do that with numpy.delete function easily as shown below:

a = np.array([[240.66666667, 171.22222222, 158.33333333],
              [218.66666667, 134.77777778, 143.33333333],
              [197.33333333, 118.55555556, 128.44444444],
              [195.22222222, 119.33333333, 126.11111111],
              [196.77777778, 118.55555556, 123.77777778],
              [183.11111111, 111.88888889, 118.88888889],
              [173.77777778, 106.77777778, 114.44444444]])

a = np.delete(a,1,axis=1)

With that piece of code, you can get the output you want.

Output: 
[[240.66666667 158.33333333]
 [218.66666667 143.33333333]
 [197.33333333 128.44444444]
 [195.22222222 126.11111111]
 [196.77777778 123.77777778]
 [183.11111111 118.88888889]
 [173.77777778 114.44444444]]

Upvotes: 0

han solo
han solo

Reputation: 6590

You can just give the columns you want like,

>>> data
array([[240.66666667, 171.22222222, 158.33333333],
       [218.66666667, 134.77777778, 143.33333333],
       [197.33333333, 118.55555556, 128.44444444],
       [195.22222222, 119.33333333, 126.11111111],
       [196.77777778, 118.55555556, 123.77777778],
       [183.11111111, 111.88888889, 118.88888889],
       [173.77777778, 106.77777778, 114.44444444]])
>>> data[:, [0,2]]
array([[240.66666667, 158.33333333],
       [218.66666667, 143.33333333],
       [197.33333333, 128.44444444],
       [195.22222222, 126.11111111],
       [196.77777778, 123.77777778],
       [183.11111111, 118.88888889],
       [173.77777778, 114.44444444]])
>>> 

Upvotes: 6

Related Questions