[英]Create minutely date_time range for fixed hours intervals during certain days using Pandas
我有一個 dataframe 有900
行,我需要創建一個從2021-01-01
到2021-01-15
的date
列,每天只有幾個小時從10:00:00
到12:00:00
,間隔是2 minutes
,
預期結果如下: 2021-01-01 10:02:00, 2021-01-01 10:04:00, ..., 2021-01-01 12:00:00, 2021-01-02 10:02:00, ..., 2021-01-02 12:00:00, ..., 2021-01-15 12:00:00
。
我的試用碼:
df['date'] = pd.date_range(datetime(2021, 1, 1, hour=10, minute=2), periods=900, freq='2min')
出去:
DatetimeIndex(['2021-01-01 10:02:00', '2021-01-01 10:04:00',
'2021-01-01 10:06:00', '2021-01-01 10:08:00',
'2021-01-01 10:10:00', '2021-01-01 10:12:00',
'2021-01-01 10:14:00', '2021-01-01 10:16:00',
'2021-01-01 10:18:00', '2021-01-01 10:20:00',
...
'2021-01-02 15:42:00', '2021-01-02 15:44:00',
'2021-01-02 15:46:00', '2021-01-02 15:48:00',
'2021-01-02 15:50:00', '2021-01-02 15:52:00',
'2021-01-02 15:54:00', '2021-01-02 15:56:00',
'2021-01-02 15:58:00', '2021-01-02 16:00:00'],
dtype='datetime64[ns]', length=900, freq='2T')
顯然,這並不像預期的那樣,我怎么能這樣做? 謝謝。
您可以在pd.date_range()
中設置start=
和end=
參數,而不是指定periods=
參數,然后使用.between_time()
,如下所示:
df = pd.DataFrame({'date':pd.date_range(start=datetime(2021, 1, 1, hour=10), end=datetime(2021, 1, 15, hour=12), freq='2min')})
df = df.set_index('date')
date_range = df.between_time('10:02:00', '12:00:00')
print(date_range)
date
2021-01-01 10:02:00
2021-01-01 10:04:00
2021-01-01 10:06:00
2021-01-01 10:08:00
...
2021-01-15 11:52:00
2021-01-15 11:54:00
2021-01-15 11:56:00
2021-01-15 11:58:00
2021-01-15 12:00:00
900 rows × 0 columns
df = pd.DataFrame({'Date':pd.date_range(datetime(2021, 1, 1, hour=10, minute=2), periods=900, freq='2min'),
'Val':[i for i in range(900)]})
df = df.set_index('Date')
result = df.between_time('10:00:00', '12:00:00')
result.info()
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 121 entries, 2021-01-01 10:02:00 to 2021-01-02 12:00:00
Data columns (total 1 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Val 121 non-null int64
dtypes: int64(1)
memory usage: 1.9 KB
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.