2017-04-26 44 views
1

我有一個df調用表,我想插入一個0作爲第一行的列表。插入第一行的問題

table: 
               A   B   C   D 
Date 
2016-04-21  0.020068  0.027631  0.006116   0.005451 
2016-04-22  0.008741  0.006732 -0.013585   0.003863 
2016-04-25 -0.020516 -0.020339 -0.007526  -0.010102 
2016-04-26  0.051630  0.032790  0.008437   0.015524 

我做了一個函數沒有創建一個長度=頭數的0的列表。

def arr(): 
    arr = [] 
    for i in range(len(list(table()))): 
     arr.append(0) 
    return arr 

pd.DataFrame([arr()],columns=list(table())) 

print(table()) 

給出了錯誤:

Shape of passed values is (1, 1), indices imply (4, 1) 

回答

1

首先需要創建新的索引值,add new rowdfloc和最後sort_index

df.loc[df.index[0] - pd.offsets.DateOffset(days=1)] = 0 
df = df.sort_index() 
print (df) 
        A   B   C   D 
Date            
2016-04-20 0.000000 0.000000 0.000000 0.000000 
2016-04-21 0.020068 0.027631 0.006116 0.005451 
2016-04-22 0.008741 0.006732 -0.013585 0.003863 
2016-04-25 -0.020516 -0.020339 -0.007526 -0.010102 
2016-04-26 0.051630 0.032790 0.008437 0.015524 
+0

總是很棒jezrael – ge00rge

+0

很高興能幫助你。 ;) – jezrael