Martin Bouhier
Martin Bouhier

Reputation: 173

Next n values in pandas loop with Python

I need the row and the next 4 rows too in loop. Any way to do that?

data = pd.read_csv('status.csv')
for i, row in data.iterrows():
    row
    row+1
    row+2
    row+3
    row+4

Upvotes: 0

Views: 499

Answers (2)

RomanPerekhrest
RomanPerekhrest

Reputation: 92874

By specifying a chunksize to pd.read_csv to consume csv data as iterator:

df = pd.read_csv('status.csv', chunksize=5)
for chunk in df:
    # do processing over chunk of 5 rows

where chunk is a Dataframe, so you might need to further for i, row in chunk.iterrows():

Upvotes: 0

Rithin Chalumuri
Rithin Chalumuri

Reputation: 1839

You can slice rows in dataframe using loc. More info here.

You can get iterator of row + next 4 rows using:

data.loc[i:i+5].iterrows()

Full Example:

for i in range(len(data.index)):
    for idx, row in data.loc[i:i+5].iterrows():
       print(idx, row)

Upvotes: 1

Related Questions