【问题标题】:IndexError: index 6 is out of bounds for axis 0 with size 6IndexError:索引 6 超出轴 0 的范围,大小为 6
【发布时间】:2020-01-17 11:23:54
【问题描述】:

我正在尝试遍历元组中的项目对,运行 Postgres 查询,然后将数据添加到 DataFrame。我的代码如下:

import pandas as pd

# Download and import WRDS, using pip if required

try:
   import wrds
except ImportError:
   !pip install wrds
   import wrds

# Connect to wrds
conn = wrds.Connection()

fd_list_most =tuple(["2013-03-01", "2013-03-03", "2013-03-19", "2013-01-29", "2013-03-28", "2013-02-22", "2013-02-27", "2013-03-14", "2013-03-01", "2013-03-18"]);

mcl1=pd.merge(most_cons_list[['gvkey','datadate','bkvlps', 'cik']],mcl,how='left',on=['gvkey'])
print(mcl1);

mcl1 输出:

    gvkey    datadate   bkvlps         cik  permco
0  008007  2013-12-31  29.0228  0000072971   21305
1  028278  2013-12-31  15.1899  0000714395   12139
2  111940  2013-12-31  13.6911  0000765207   16649
3  157955  2013-12-31  28.0769  0001273813   45077
4  180169  2013-12-31  10.4775  0001390312   53031
5  184167  2013-12-31  18.1538  0000860413   53368
# Loop over each pair of filing date and CIK and retrieve stock price for 7 days either side of filing date

mcl2=pd.DataFrame();


for i in range(len(fd_list_most)):
    stmt3="""
    select permco, ret, retx, date(date) as date
    FROM crsp.dsf
    where permco= {}
    and  date < date '{}' + integer '7'
    and date > date '{}' - integer '7'
    """.format(mcl['permco'].values[i],fd_list_most[i],fd_list_most[i])
    mcl2=mcl2.append(conn.raw_sql(stmt3))

print(mcl2)

错误:

IndexError                                Traceback (most recent call last)
<ipython-input-37-31f1dfe1daea> in <module>
     11     and  date < date '{}' + integer '7'
     12     and date > date '{}' - integer '7'
---> 13     """.format(mcl['permco'].values[i],fd_list_most[i],fd_list_most[i])
     14     mcl2=mcl2.append(conn.raw_sql(stmt3))
     15 

IndexError: index 6 is out of bounds for axis 0 with size 6

这是来自导师的示例代码,它适用于他输入的数据,但不适用于我的数据。 我可以看到我的索引长度有问题,但我不确定如何解决。 我会很感激任何帮助。我是初学者,所以我并不总是理解更复杂的解决方案。我已经查看了这个问题,并尝试了这些IndexError: index 1 is out of bounds for axis 0 with size 1/ForwardEulerindex 100 is out of bounds for axis 0 with size 100,但它们对我没有用,可能是因为我不明白如何将解决方案应用于我的问题。 谢谢

【问题讨论】:

    标签: python pandas loops


    【解决方案1】:

    您的 DataFrame 看起来只有 6 个条目,而您正在迭代一个包含更多条目的元组。在您的 for 语句中,您可以将其更改为遍历 mc12 的行。

    我不推荐使用df.iterrows(),但在这种情况下,它看起来很合适。在这里查看:df.iterrows()

    另外,您确定此语句符合您的预期吗? mcl2=mcl2.append(conn.raw_sql(stmt3)) .你没有发布关于那个,所以我不会在这里讨论它。

    【讨论】:

    • 谢谢,这就是问题所在。我请求了不存在的数据,所以我的 DataFrame 比我的元组小。不幸的是,mcl1 的行不包含与元组相同的数据。有没有一种简单的方法可以解决这个问题,我可以使用元组但有 NaN 或类似的东西来代替原本会存在的数据?
    猜你喜欢
    • 2019-03-01
    • 1970-01-01
    • 2017-02-16
    • 2021-11-24
    • 2020-04-24
    • 2016-07-29
    • 2021-07-17
    • 2021-05-24
    • 2018-07-23
    相关资源
    最近更新 更多