Home > Net >  IndexError after trying to iter over rows and columns
IndexError after trying to iter over rows and columns

Time:02-26

Imagine a table with rows and columns. I want to read the table row by row. I don't understand what has to get fixed and what's the best way to do so:

import pandas as pd

num_rows = 4
num_cols = 5
value = "test"

for i in range(num_rows):
    s = pd.Series()
    for c in range(num_cols):
        s[c] = value

Output:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
  File "c:\Users\chris\projects\stockfinder\venv\lib\site-packages\pandas\core\series.py", line 1067, in __setitem__
    values[key] = value
IndexError: index 0 is out of bounds for axis 0 with size 0

CodePudding user response:

Use:

import pandas as pd
num_rows = 4
num_cols = 5
value = "test"

for i in range(num_rows):

    #here is the problem
    s = pd.Series(index=range(num_cols))

    for c in range(num_cols):
        s[c] = value
  • Related