1

So I have a piece of code that is iterating through a dataframe switched to tuples then iterating through each value after the first one. Everything was working fine yesterday, but today, with certain rows it is not excluding the first index and I have no idea why.

Here is the code:

for rows in data.itertuples():
    r = int(rows[0]) + 1
    for i in rows[1:]:
        c = rows.index(i)
        print r, i, c, int(rows.index(i)), rows

I copied the print out of the iteration of the first 2 rows. The first row worked perfectly. The second row had an issue. What is expected is that c would be set to 1 for the first element that it picked up row[1], but instead it is 0. This is randomly happening through out the rows of dataframe. Does anyone have any ideas why the for loop is not skipping past the first element?

1 3 1 1 (0, 3, 27000, '1060', 'QMS', 'TEST', 'DAY', 'LMT')

1 1 3

1 27000 2 2 (0, 3, 27000, '1060', 'QMS', 'TEST', 'DAY', 'LMT')

1 2 27000

1 1060 3 3 (0, 3, 27000, '1060', 'QMS', 'TEST', 'DAY', 'LMT')

1 3 1060

1 QMS 4 4 (0, 3, 27000, '1060', 'QMS', 'TEST', 'DAY', 'LMT')

1 4 QMS

1 ARCA 5 5 (0, 3, 27000, '1060', 'QMS', 'TEST', 'DAY', 'LMT')

1 5 ARCA

1 DAY 6 6 (0, 3, 27000, '1060', 'QMS', 'TEST', 'DAY', 'LMT')

1 6 DAY

1 LMT 7 7 (0, 3, 27000, '1060', 'QMS', 'TEST', 'DAY', 'LMT')

1 7 LMT

**2 1 0 0 (1, 1, 3500, '1060', 'QMS', 'TEST', 'DAY', 'LMT')**

2 0 1

2 3500 2 2 (1, 1, 3500, '1060', 'QMS', 'TEST', 'DAY', 'LMT')

2 2 3500

2 1060 3 3 (1, 1, 3500, '1060', 'QMS', 'TEST', 'DAY', 'LMT')

1 Answer 1

3

rows.index(i) will find the first item in rows that has the value i. When you reach your second rows collection, rows[0] equals one, so rows.index(1) is zero, even though rows[1] also equals one.

If you just want to iterate through the indices and values of an iterable, I suggest using enumerate.

for rows in data.itertuples():
    r = int(rows[0]) + 1
    for c, i in enumerate(rows):
        #skip the first value
        if c == 0:
            continue
        #do whatever here

Or

for rows in data.itertuples():
    r = int(rows[0]) + 1
    for c, i in enumerate(rows[1:], 1): #skip the first item implicitly
        #do whatever here
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.