按月份分列日期列表

时间:2016-09-17 16:49:01

标签: python list datetime pandas group-by

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)]

或作为词典

expected_grouped_bymonth = {
    "2015-12": #dates_in_the_list_occured_in_december_2015) , ...
    "2013-1", #january2013dates)}

我有一个表示日期的字符串列表。我想要的是一个元组列表或字典,每年或每月计算出现次数。我试图做的是与groupby相关的事情。我根据TimeGrouper函数无法理解如何使用groupby

引发的例外是:

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有关。)

1 个答案:

答案 0 :(得分:2)

如果您想了解每月和每年日期的频率,您可以使用 defaulftdict

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",
        ]

from collections import defaultdict

dates = defaultdict(lambda:defaultdict(int))

for s in raw_data:
    k, v = s.rsplit("-", 1)
    dates[k][v] += 1

print(dates)

或者,如果您只想按月份分组日期列表

dates = defaultdict(list)

for s in raw_data:
    k, v = s.rsplit("-", 1)
    dates[k].append(v)

print(dates)