【问题标题】:Group a list of dates by month, year按月、年对日期列表进行分组
【发布时间】: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


【解决方案1】:

如果您想获取某个日期每月和每年出现的频率,您可以使用 defaultdict

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)

【讨论】:

  • 非常感谢!!!请问您是否有使用 groupby 功能的等效方式?这是我怀疑的主要目的!
  • @LeoCella,您的意思是将我们分组的日期放入 df 并应用 groupby 还是只是传递日期然后执行 groupby?
  • 从日期列表开始,使用 groupby 按月或年聚合它们,并保留它们的频率计数。如果有必要,我也可以从字典 {initialdate1:1,..initialdaten:1} 开始,在 groupby 中使用 like sum 函数。不知道有没有可能,只是一个类似于SQL过程的思路。
猜你喜欢
  • 2018-01-07
  • 1970-01-01
  • 2012-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-15
  • 2013-02-12
相关资源
最近更新 更多