【发布时间】:2017-01-25 17:40:32
【问题描述】:
raw_data = ["2015-12-31", "2015-12-1" , "2015-1-1",
"2014-12-31", "2014-12-1" , "2014-1-1",
"2013-12-31", "2013-12-1" , "2013-1-1",]
expected_grouped_bymonth = [("2015-12", #dates_in_the_list_occured_in_december_2015)
, ...
("2013-1", #january2013dates)]
OR 作为字典
expected_grouped_bymonth = {
"2015-12": #dates_in_the_list_occured_in_december_2015) , ...
"2013-1", #january2013dates)}
我有一个代表日期的字符串列表。我想要的是一个元组列表或字典,它计算每年或每月出现的次数。我试图做的是与groupby 相关的事情。根据groupby函数,我无法理解如何使用TimeGrouper。
引发的异常是:
TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex,
but got an instance of 'RangeIndex'
from itertools import groupby
for el in data:
if 'Real rates - Real volatilities' in el['scenario']:
counter += 1
real_records_dates.append(pd.to_datetime(el['refDate']))
print("Thera are {} real records.".format(counter))
BY_YEAR = 'Y'
BY_MONTH = 'M'
BY_DAY = 'D'
real_records_df = pd.DataFrame(pd.Series(real_records_dates))
real_records_df.groupby(pd.TimeGrouper(freq=BY_MONTH))
(如果更容易的话,您也可以假设从字典 og {date1:1, date2:2, ...} 开始。我的问题仅与 groupby 有关。)
【问题讨论】:
-
请edit您的问题,并添加
data中的确切内容的示例。 -
你期望输出什么?
-
expected_grouped_bymonth;基本上我需要按月/年对日期列表进行分组,作为一个分组函数,我需要计算活动月/年中有多少日期。
标签: python list datetime pandas group-by