简体   繁体   中英

Select rows at intervals of one minute from a datetime column

I got the datetime and price data of a stock eg

df = pd.DataFrame({ 'datetime' : ['2016-10-03 11:00:00', '2016-10-03 11:00:20','2016-10-03 11:00:24','2016-10-03 11:01:05','2016-10-03 11:01:14','2016-10-03 11:02:00','2016-10-03 11:02:28','2016-10-03 11:03:32','2016-10-03 11:04:26','2016-10-03 11:06:10'], 
                   'price' : [10.02, 10.32, 10.32, 10.21, 10.45, 10.56, 10.68, 10.80, 11.01, 10.98]})

I want to buy 100 shares of stocks every minute (ie 2016-10-03 11:00 - price at 10.02 * 100 shares, 2016-10-03 11:01 - price at 10.21 * 100 shares and so on)

is there a way to achieve this without merging the data? (I need the data in the unit of every second for the next step)

IIUC, you can use pd.to_datetime + resample + first :

df.assign(datetime=pd.to_datetime(df.datetime))\
        .set_index('datetime').resample('1T').first() * 100
                      price
datetime                   
2016-10-03 11:00:00  1002.0
2016-10-03 11:01:00  1021.0
2016-10-03 11:02:00  1056.0
2016-10-03 11:03:00  1080.0
2016-10-03 11:04:00  1101.0
2016-10-03 11:05:00     NaN
2016-10-03 11:06:00  1098.0

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