我需要计算2015-01-01和2015-12-31之间每天晚上21:30到04:30之间的一些事件的总和?
如何以最优雅但又简单有效的方式使用Pandas来实现它?
示例结果表应类似于以下内容:
count
2015-04-01 38 (events between 2015-03-31 21:30 and 2015-04-01 04:30)
2015-04-02 15 (events between 2015-04-01 21:30 and 2015-04-02 04:30)
2015-04-03 27 (events between 2015-04-02 21:30 and 2015-04-03 04:30)
感谢您提供任何帮助和建议。
答案 0 :(得分:1)
您可以使用:
df = pd.DataFrame({'a':['2015-04-01 15:00','2015-04-01 23:00','2015-04-01 04:00','2015-04-02 03:00','2015-05-02 16:00','2015-04-03 02:00'],
'b':[2,4,3,1,7,10]})
df['a'] = pd.to_datetime(df.a)
print (df)
a b
0 2015-04-01 15:00:00 2
1 2015-04-01 23:00:00 4
2 2015-04-01 04:00:00 3
3 2015-04-02 03:00:00 1
4 2015-05-02 16:00:00 7
5 2015-04-03 02:00:00 10
创建DatetimeIndex
:
start = pd.to_datetime('2015-04-01')
d = pd.date_range(start, periods=3)
print (d)
DatetimeIndex(['2015-04-01', '2015-04-02', '2015-04-03'], dtype='datetime64[ns]', freq='D')
按DatetimeIndex
循环,按boolean indexing
选择所有行并获取len
:
for dat in d:
date_sum = len(df.ix[(df.a >= dat.date()+pd.offsets.DateOffset(hours=21, minutes=30)) &
(df.a <= dat.date()+pd.offsets.DateOffset(days=1, hours=4, minutes=30)),'b'])
print (date_sum)
print (dat.date())
2
2015-04-01
1
2015-04-02
0
通过dict comprehension创建新的Series
:
out = { dat.date(): len(df.ix[(df.a >= dat.date() + pd.offsets.DateOffset(hours=21, minutes=30)) & (df.a <= dat.date() + pd.offsets.DateOffset(days=1, hours=4, minutes=30)), 'b']) for dat in d}
s = pd.Series(out)
print (s)
2015-04-01 2
2015-04-02 1
2015-04-03 0
dtype: int64