Home > Net >  How to return every N alternate rows from a pandas dataframe?
How to return every N alternate rows from a pandas dataframe?

Time:11-10

Let's say I have a dataframe with 1000 rows. Is there an easy way of slicing the datframe in sucha way that the resulting datframe consisits of alternating N rows?

For example, I want rows 1-100, 200-300, 400-500, ....and so on and skip 100 rows in between and create a new dataframe out of this.

I can do this by storing each individial slice first into a new dataframe and then append at the end, but I was wondering if there a much simpler way to do this.

CodePudding user response:

You can use:

import numpy as np
out = df[np.arange(len(df)) 0<100]

for the demo here is an example with 1-10, 20-30, etc.

df = pd.DataFrame(index=range(100))
out = df[np.arange(len(df)) <10]
out.index

output:

Int64Index([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, # rows  1-10
            20, 21, 22, 23, 24, 25, 26, 27, 28, 29, # rows 20-30
            40, 41, 42, 43, 44, 45, 46, 47, 48, 49, # rows 30-50
            60, 61, 62, 63, 64, 65, 66, 67, 68, 69, # rows 50-70
            80, 81, 82, 83, 84, 85, 86, 87, 88, 89],# rows 80-90
           dtype='int64')

CodePudding user response:

You can use list comprehension and a simple math operation to select specific rows.
If you don't know, % is the modulo operation in Python, which returns the remainder of a division between two numbers.
The int function, instead, eliminates the decimal digits from a number.

Let df be your dataframe and N be your interval (in your example N=100):

N = 100

df.loc[[i for i in range(df.shape[0]) if int(i/N) % 2 == 0]]

This will return rows with indexes 0-99, 200-299, 400-499, ...

  • Related