Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy every nth column of a numpy array

How would you copy the first element and every element of the nth column in another array?

For example, supposed you have the array below:

array{[1,2,3,4,5],
      [1,2,3,4,5],
      [1,2,3,4,5]}

I want to choose the first element and every 2nd element so I would have:

array{[1,3,5],
      [1,3,5],
      [1,3,5]}
like image 889
noobiejp Avatar asked Feb 02 '26 15:02

noobiejp


1 Answers

You can use slicing against the columns

>>> a
array([[1, 2, 3, 4, 5],
       [1, 2, 3, 4, 5],
       [1, 2, 3, 4, 5]])

>>> a[:, ::2]
array([[1, 3, 5],
       [1, 3, 5],
       [1, 3, 5]])

As mentioned by @tobias_k if you want to make an actual copy of this sliced array, you can use numpy.copy to make sure modifications don't affect the original array

>>> np.copy(a[:, ::2])
array([[1, 3, 5],
       [1, 3, 5],
       [1, 3, 5]])
like image 154
Cory Kramer Avatar answered Feb 05 '26 05:02

Cory Kramer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!