Home > Software engineering >  how to extract every nth row from numpy array
how to extract every nth row from numpy array

Time:02-02

I have a numpy array and I want to extract every 3rd rows from it

input

0.00    1.0000 
0.34    1.0000 
0.68    1.0000 
1.01    1.0000
1.35    1.0000
5.62    2.0000

I need to extract every 3rd row so that expected output will be

0.68    1.0000 
5.62    2.0000

My code:

import numpy as np
a=np.loadtxt('input.txt')
out=a[::3]

But it gives different result.Hope experts will guide me.Thanks.

CodePudding user response:

When undefined, the starting point of a (positive) slice is the first item.

You need to slice starting on the n-1th item:

N = 3
out = a[N-1::N]

Output:

array([[0.68, 1.  ],
       [5.62, 2.  ]])
  • Related