[英]Inserting data from dataframe into numpy array
我將數據從具有55行的數據幀df
插入到numpy數組matrix_of_coupons_and_facevalues
,形狀為(53,50)。 我這樣做是使用下面的代碼。 但是,我得到錯誤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
謝謝
對於任何未來的訪客,這是發生的事情:
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
或者你可以使用pandas reset_index
In [18]: df.drop(1).reset_index()
Out[18]:
index x y
0 0 1 2
1 2 5 6
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.