简体   繁体   中英

Append data to DataFrame at specific interval in Python

I want to append a random number to a dataframe every 3 seconds, X amount of times. The time stamp format is, hh:mm:ss, and it should populate in column A (Time), and the random number should populate in column B (Price). I'm struggling with the loop to append a time stamp at the 3 second interval.

import numpy as np
import pandas as pd
import time
import datetime

def main(): 

    ts = time.time()
    st = datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S')
    data = [[st, '$' + str(np.random.randint(12, 25))]]
    df = pd.DataFrame(data)
    df = pd.DataFrame(data, columns = ['Time', 'Price'])
    print(df)

main()

The above code prints this:

       Time Price
0  20:56:36   $10

The result should look like this:

       Time Price
0  20:56:36   $10
1  20:59:36   $16
2  21:02:36   $12
3  21:05:36   $18

It appears you are not having any criteria for the 3 minutes append in your code at the moment ?

If you want to invoke an interval job every x minutes, you can try the apscheduler==2.1.2 (package) ...

via pip install apscheduler==2.1.2

here is a small template:

import numpy as np
import pandas as pd
import time
import datetime
from apscheduler.scheduler import Scheduler
#pip install apscheduler==2.1.2



def append(): 
    #Write the logic what you want to do every x minutes

    #End the function

sched = Scheduler()
sched.start()

sched.add_interval_job(append, minutes=x)

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