0

I want to calculate difference between rows in python. I konw i can use diff() to do that. But i want to try to use a "for loop". I try the following codes, but i get error "KeyError: 2" in line if pdf.loc[i+1,'A'] != pdf.loc[i,'A']:

If i want to do the following calculation, how can i do it, please Help.

print(loc[2,'A'] * loc[1,'A'] + 3)

print(loc[3,'A'] * loc[2,'A'] + 3)

print(loc[4,'A'] * loc[3,'A'] + 3)

...

print(loc[i,'A'] * loc[i-1,'A'] + 3)

The code which showed error with "KeyError: 2"

for i, dura in pdf.iterrows():

     if i < pdf.shape[0]:
         if pdf.loc[i+1,'A'] != pdf.loc[i,'A']:
            print("a")
         else:
            print("b")
     else:
         print("finished")
Ryou
  • 255
  • 5
  • 17

1 Answers1

0

iterrows() is one of the slowest ways to iterate through the pandas dataframe. Use itertuples() instead (there are other faster options )

for row in df.itertuples():
    if row.Index < df.shape[0]-1:
        if df.at[row.Index+1,'A']!= row.A:
            print("a")
        else:
            print("b")
     else:
         print("finished")
padu
  • 689
  • 4
  • 10