Python Forum

Full Version: How define iteration interval increment
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I want to iterate through df rows and increase the iteration step increment by 3 (increment i=i+3 on each iteration). I use the below code, but it's not happening what I want to do. Please help me, someone.

import pandas as pd
import csv
input=r'D:\PythonCodes\correctiofactordata.csv'
df=pd.read_csv(input)
for i, row in df.iterrows():
    print(i)
    i+=3
my input data:

Time_golden	Golden	is_golden	Factor
20-03-2019 10:24	98.6	golden	1.0
20-03-2019 11:10	97.0	golden	1.3
20-03-2019 13:13	96.0	golden	1.5
21-03-2019 13:43	95.0	golden	0.95
23-03-2019 10:37	94.6	golden	0.96
23-03-2019 18:43	93.0	golden	1.0
24-03-2019 22:19	92.0	golden	1.3
25-03-2019 09:23	90.0	golden	1.5
26-03-2019 11:42	89.0	golden	0.95
27-03-2019 20:32	87.3	golden	0.96
27-03-2019 23:42	86.0	golden	1.5
28-03-2019 00:52	84.0	golden	0.95
28-03-2019 03:40	82.3	golden	0.96
21-03-2019 10:34	83.0	notgolden	1.0
24-03-2019 16:37	80.0	notgolden	1.3
24-03-2019 21:42	73.0	notgolden	0.95
27-03-2019 21:02	60.0	notgolden	0.96
28-03-2019 02:42	53.0	notgolden	1.0
20-03-2019 10:24	98.6	golden	1.3
20-03-2019 11:10	97.0	golden	1.5
20-03-2019 13:13	96.0	golden	0.95
21-03-2019 13:43	95.0	golden	0.96
23-03-2019 10:37	94.6	golden	1.5
23-03-2019 18:43	93.0	golden	0.95
24-03-2019 22:19	92.0	golden	0.96
25-03-2019 09:23	90.0	golden	1.0
26-03-2019 11:42	89.0	golden	1.3
27-03-2019 20:32	87.3	golden	1.3
27-03-2019 23:42	86.0	golden	1.0
Changing i isn't going to work at all. The variable i just gets reassigned through the loop, so nothing you do to that name in the loop has any effect on the next iteration. I would just continue until you get what you want:

for i, row in df.iterrows():
    if i % 3 != 1:
        continue
    print(i)
Thanks, It works, can you help explain the logic?
% is the modulus operator. That is, the remainder after division. So 1 % 3 = 1, 2 % 3 = 2, 3 % 3 = 0, 4 % 3 = 1, and so on. So every third time it's equal to one (you could choose 0 or 2 to get a different starting row). The other times you use continue, which skips to the next iteration of the loop.
can't we specify like in Matlab:

for i=1:3:size(df,1)
disp(i)
end

Here,3 is the step size which increment "i" on each iteration by 3.
Starting with one, when it completes the first iteration "i" becomes 4, then 7
We can specify that sort of thing with a range(), but I didn't see anything equivalent in iterrows. I generally avoid using range to iterate over indexes, preferring to iterate directly. You could do it with a range like this:

for row_index in range(0, len(data), 3):
    row = df.ix[row_index]
    print(row)
Although I think islice from the itertools built-in package might work better:

for index, row in itertools.islice(data.iterrows(), 0, len(d), 3):
    print(row)