简体   繁体   中英

How to add new row in time series dataframe

My dataframe has an index column of dates and one column

             var
date 
2020-03-10   77
2020-03-11   88
2020-03-12   99 

I have an array and I want to append it to the dataframe one by one. I have tried a few methods but anything isn't working. my code is something like this

for i in range(20):
   x=i*i
   df.append(x)

After each iteration dataframe needs to be appended with x value. Final output:

             var
date 
2020-03-10   77
2020-03-11   88
2020-03-12   99 
2020-03-13   1
2020-03-14   4
2020-03-15   9
.
.
. 20 times

Will be grateful for any suggestions.

Try this

tmpdf = pd.DataFrame({"var":[77,88,99]},index=pd.date_range("2020-03-10",periods=3,freq='D'))
for i in range(1,21):
    idx = tmpdf.tail(1).index[0] + pd.Timedelta(days=1)
    tmpdf.loc[idx] = i*i

output

2020-03-10   77
2020-03-11   88
2020-03-12   99
2020-03-13    1
2020-03-14    4
2020-03-15    9
2020-03-16   16
2020-03-17   25
2020-03-18   36
2020-03-19   49
2020-03-20   64
2020-03-21   81
2020-03-22  100
2020-03-23  121
2020-03-24  144
2020-03-25  169
2020-03-26  196
2020-03-27  225
2020-03-28  256
2020-03-29  289
2020-03-30  324
2020-03-31  361
2020-04-01  400

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM