0

Please help. I have the following data frame with 5 columns. The first row throws an Index out of bounds error even though there are supposed to be 5 columns - if you include the area marked in red. Not quite sure how to iterate this?:

enter image description here

index 4 is out of bounds for axis 0 with size 4

Here is the code I am using:

for index, row in df.iterrows():
    print(row.index[0],row.index[1],row.index[2],row.index[3],row.index[4])
ibexy
  • 609
  • 3
  • 16
  • 34
  • Check the length of the row before you expand it, or skip the first row. If you need the headers, take them straight out of the first row before entering the loop. – sal Feb 07 '21 at 22:37
  • 2
    seems the first column is matched as ID - not sure how you created the df - may you can add this information – Prometheus Feb 07 '21 at 22:39
  • @sal, any chance of getting a sample code? – ibexy Feb 07 '21 at 22:56
  • @Prometheus I did not create the df. I get the object already made. – ibexy Feb 07 '21 at 23:25
  • Panda's not my area, however it might be that you are counting dimensions wrong. Give this a try: `for index, row in df.iterrows(): print(row['Income'], row['Expenses'])` If that doesn't work, I give up to more expert hands :-) Also check this out: https://stackoverflow.com/questions/16476924/how-to-iterate-over-rows-in-a-dataframe-in-pandas – sal Feb 08 '21 at 00:37
  • How do you know the dataframe is supposed to contain 5 columns? As @Prometheus said, the first column is matched as ID. – mightyandweakcoder Feb 08 '21 at 03:04

1 Answers1

0

In the end I had to adopt a crude method of first writing the data frame to a CSV file and then reading that file.

Fortunately the empty header (marked in red in the table) returns as a blank ('') that I can easily identify and replace with a value:

Am sure this is not the best solution but here goes:

df.to_csv('x.csv')
with open('x.csv') as csvfile:
    dt = csv.reader(csvfile)
    for row in dt:
        print(row)

Output for row1/col1 is an empty string. This works for me.

ibexy
  • 609
  • 3
  • 16
  • 34