我的熊猫数据框的格式为
print(ts.head())
id start_datetime end_datetime
0 2018-09-19 00:00:00 2018-09-19 03:00:00
1 2018-09-19 01:00:00 2018-09-19 03:00:00
2 2018-09-19 01:30:00 2018-09-19 03:00:00
3 2018-09-19 02:14:00 2018-09-19 03:00:00
4 2018-09-19 02:23:00 2018-09-19 03:00:00
我想用单个列制作一个带有日期时间索引(每小时频率)的数据框。该列为每个索引计算原始数据框的行中有多少行在其start_datetime和end_datetime值之间包含此索引。
我首先以每小时的频率制作df,该频率在适当的时间开始和结束:
ts = df.select('start_datetime','end_datetime').toPandas()
idx = pd.DatetimeIndex(freq="h", start="2018-09-19", end = '2018-11-18
18:00:00')
df_hourly = pd.DataFrame(index=idx)
df_hourly.head()
id
2018-09-19 00:00:00
2018-09-19 01:00:00
2018-09-19 02:00:00
2018-09-19 03:00:00
2018-09-19 04:00:00
现在,我需要为每一行计算介于其之间的原始数据帧的行数。我正在尝试对列的值使用numpy,但是我敢肯定有一种相当不错的方法来做到这一点。
答案 0 :(得分:0)
我正在使用numpy
广播
s1 = df.start_datetime.values
s2 = df.end_datetime.values
s = df_hourly.index.values[:, None]
df_hourly['Value'] = np.sum((s1 <= s) & (s2 >= s), 1)
df['Value'] = np.sum((s1 <= s) & (s2 >= s), 0)