0

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
Christian
  • 515
  • 1
  • 6
  • 17
  • what are you trying to do? –  Feb 26 '22 at 09:01
  • I'm trying to read the content of each field of a given matrix which is not a pandas object yet. – Christian Feb 26 '22 at 09:04
  • https://stackoverflow.com/a/13332682/2111778 Does this help answer your question? – xjcl Feb 26 '22 at 09:11
  • it seems you're trying to build a Series object row by row. Is there any reason why you can't just pass your data once to the constructor? –  Feb 26 '22 at 09:11

1 Answers1

2

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
TheFaultInOurStars
  • 3,464
  • 1
  • 8
  • 29
keramat
  • 4,328
  • 6
  • 25
  • 38