我是pandas / python的新手:
我有一个由SELECT * FROM @table
ORDER BY (CASE @SortItem WHEN 'number asc' THEN number END) asc,
(CASE @SortItem WHEN 'name desc' THEN name END) desc
对象索引的dataframe
(events.number)。
我试图在每个星期一(或其他特定工作日)每小时提取一次事件计数。我写道:
datetime
但这不能正常工作。
我可以放弃" hour_tally_monday = events.number.groupby(lambda x: (x.hour & x.weekday==0) ).count()
"它可以工作,但可能会使用框架中的所有日子。什么是正确的(最简单的)语法在星期一平均?
答案 0 :(得分:3)
我认为您需要先使用boolean indexing
过滤数据框,然后将groupby
与size
一起使用:
import pandas as pd
start = pd.to_datetime('2016-02-01')
end = pd.to_datetime('2016-02-25')
rng = pd.date_range(start, end, freq='12H')
events = pd.DataFrame({'number': [1] * 20 + [2] * 15 + [3] * 14}, index=rng)
print events
number
2016-02-01 00:00:00 1
2016-02-01 12:00:00 1
2016-02-02 00:00:00 1
2016-02-02 12:00:00 1
2016-02-03 00:00:00 1
2016-02-03 12:00:00 1
2016-02-04 00:00:00 1
2016-02-04 12:00:00 1
2016-02-05 00:00:00 1
2016-02-05 12:00:00 1
2016-02-06 00:00:00 1
2016-02-06 12:00:00 1
2016-02-07 00:00:00 1
...
...
filtered = events[events.index.weekday == 0]
print filtered
number
2016-02-01 00:00:00 1
2016-02-01 12:00:00 1
2016-02-08 00:00:00 1
2016-02-08 12:00:00 1
2016-02-15 00:00:00 2
2016-02-15 12:00:00 2
2016-02-22 00:00:00 3
2016-02-22 12:00:00 3
在版本0.18.1
中,您可以使用新方法DatetimeIndex.weekday_name
:
filtered = events[events.index.weekday_name == 'Monday']
print filtered
number
2016-02-01 00:00:00 1
2016-02-01 12:00:00 1
2016-02-08 00:00:00 1
2016-02-08 12:00:00 1
2016-02-15 00:00:00 2
2016-02-15 12:00:00 2
2016-02-22 00:00:00 3
2016-02-22 12:00:00 3
print filtered.groupby(filtered.index.hour).size()
0 4
12 4
dtype: int64