在 Pandas 中是否有一种方法可以创建一个时间序列,该时间序列由一段时间内每一天的选定时钟时间组成?例如:我们将 2018 年的所有日子作为我们的日期,时间(时钟)有 4 个不同的时间,例如 [09:00, 10:35, 14:00, 15:50]
。
所以我想要的是像这样的时间序列:
2018-01-01 09:00
2018-01-01 10:35
2018-01-01 14:00
2018-01-01 15:50
2018-01-02 09:00
2018-01-02 10:35
2018-01-02 14:00
2018-01-02 15:50
2018-01-03 09:00
...
TIA,
最佳答案
你可以做这样的事情,这比循环要快得多:
1.) 创建日期列表:
In [34]: start_dt = '2018-01-01'
# For whole year, use periods=365
In [45]: days_list = pd.date_range(pd.to_datetime(start_dt), periods=3)
In [59]: days_list = [i.date() for i in days_list] # Keeping only date part
2.) 创建时间列表:
In [38]: timelist = ['09:00', '10:35', '14:00', '15:50']
3.) 通过将 days_list
中的每个元素重复 4 次来扩展列表,每次一个:
In [60]: import numpy as np
In [61]: days_list = np.repeat(days_list, 4)
4.) 通过将时间列表乘以 days_list 中的唯一日期来扩展时间列表,使其具有与 days_list 相同的长度:
因此,由于我们在创建 days_list 时使用了 periods=3
。因此,将时间列表延长相同的因素;
In [64]: timelist = timelist * 3
5.) 创建数据框:
In [65]: df = pd.DataFrame()
In [66]: df['Date'] = days_list
In [68]: df['time'] = timelist
最终输出:
In [78]: df
Out[78]:
Date time
0 2018-01-01 09:00
1 2018-01-01 10:35
2 2018-01-01 14:00
3 2018-01-01 15:50
4 2018-01-02 09:00
5 2018-01-02 10:35
6 2018-01-02 14:00
7 2018-01-02 15:50
8 2018-01-03 09:00
9 2018-01-03 10:35
10 2018-01-03 14:00
11 2018-01-03 15:50
关于Python Pandas - 非连续时间序列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53790807/