Home > Software design >  Accessing a value by index in enumerate for-loop
Accessing a value by index in enumerate for-loop

Time:04-29

I'm trying to access a previous value (by index) in a for loop. So I have a condition where I want to compare the value of i to i-1, but don't think I'm doing this correctly:

for i, f in enumerate(df[col1]):
  if f[i] < f[i-1]:
      do something

So in the above code I would try to compare df[col1][1] to df[col][0]. Completely hypothetical by the way. I just need to figure out the correct way to access values by index for in enumerate. Thanks

CodePudding user response:

Everything looks good so far. If you were to use more descriptive names it will make it easier to understand. With enumerate, you are declaring it correctly, and ordering your variables well. The only thing I see will come up is when you use [i-1] to index your list/dictionary. enumerate() begins it's count at 0, so you will end up with a negative index, and it will raise an error. You can instead use "for i, f in enumerate(df[col1], 1). The second param is the starting key it will use when enumerating over each object. Let me know how that works for you!

CodePudding user response:

If you want to simply access the column's element from its index, you can simply do and or try this:

for i, f in enumerate(df['col1']):
   if df['col1'][i] < df['col1'][i - 1]:
       # do something you desire

Tell me if it works.

  • Related