从DataFrame中将数据插入到NumPy数组中。

3

我正在将一个有55行的dataframe df 中的数据插入到一个形状为 (55,60) 的numpy数组 matrix_of_coupons_and_facevalues中,使用以下代码。然而,我遇到了错误IndexError: index 55 is out of bounds for axis 0 with size 55。变量months_to_maturity 包含数字[6:6:330]

for (i,row) in df.iterrows():
    matrix_of_coupons_and_facevalues[i,0:(row.months_to_maturity/ 6)-1] = 1/2
    matrix_of_coupons_and_facevalues[i,(row.months_to_maturity/6)-1] = 3/2

谢谢您


你能确认一下df确实有55行吗?从代码的样子来看,i似乎是取了55的值,这只有在df有超过55行的情况下才可能发生。也许你可以尝试像这样打印一下 print(len(list(df.iterrows()))) 看看是否确实是55。 - brenns10
请问您能否展示一下您的数据框长什么样子?特别是索引。 - Anand S Kumar
@brenns10的代码print(len(list(df.iterrows())))的结果是55。 - user131983
有趣。我想到一个问题,如果您从数据框中删除了任何行,则索引不会像您预期的那样从0到54,而是会有间隙。如果您检查一下索引包含什么,就像@AnandSKumar建议的那样,这将非常有帮助。 - brenns10
我刚意识到需要重置数据框的索引。现在已经排序好了。谢谢。 - user131983
2个回答

2
任何未来的访问者,以下是发生的情况:
DataFrame的索引用于唯一标识每一行,因此当您删除一行时,该索引将被删除,并且您会在索引中留下“间隙”。当您拥有有意义的索引时,这非常好。但是,当您只想对行进行编号时,这不是您想要的结果。在这种情况下,df包含55行,但索引中有空洞,因此最大索引值大于55,导致矩阵出现IndexError。例如:
In [1]: import pandas as pd

In [2]: df = pd.DataFrame([[1,2],[3,4],[5,6]], columns=['x','y'])

In [3]: df
Out[3]: 
   x  y
0  1  2
1  3  4
2  5  6

In [4]: df = df.drop(1)

In [5]: df
Out[5]: 
   x  y
0  1  2
2  5  6

为了解决这个问题,你可以简单地将索引重新分配为包含正确数字范围的列表:
In [6]: df.index = list(range(len(df.index)))

In [7]: df
Out[7]: 
   x  y
0  1  2
1  5  6

0

或者你可以使用pandas reset_index

In [18]: df.drop(1).reset_index()
Out[18]:
   index  x  y
0      0  1  2
1      2  5  6

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接