【问题标题】:IndexError after trying to iter over rows and columns尝试遍历行和列后的 IndexError
【发布时间】:2022-02-26 17:19:16
【问题描述】:

想象一个有行和列的表格。我想逐行阅读表格。我不明白必须修复什么以及最好的方法是什么:

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

输出:

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

【问题讨论】:

  • 你想做什么?
  • 我正在尝试读取给定矩阵的每个字段的内容,该矩阵还不是熊猫对象。
  • stackoverflow.com/a/13332682/2111778 这有助于回答您的问题吗?
  • 您似乎正在尝试逐行构建系列对象。有什么理由不能只将数据传递给构造函数一次?

标签: python pandas


【解决方案1】:

用途:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-15
    • 2013-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多