2016-09-17 94 views
0
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相關的東西。根據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。)

+0

請[編輯]你的問題,並添加的究竟是什麼在'data'樣本。 – martineau

+0

你期待什麼作爲輸出? –

+0

expected_grouped_bymonth;基本上我需要將日期列表按月份/或年份分組,並且作爲一個組函數,我需要計算活動月份/年份中發生的日期數。 – LeoCella

回答

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) 
+0

非常感謝!我可以問你有沒有和groupby功能一樣的方法嗎? 這是我懷疑的主要目的! – LeoCella

+0

@LeoCella,你的意思是把我們的分組日期放在一個df中,然後應用groupby或者只是傳遞日期,然後執行groupby? –

+0

從日期列表開始,使用groupby將它們按月份或年份進行彙總,並保持其頻率計數。如果有必要,我還可以從字典{initialdate1:​​1,.. initialdaten:1}開始,使用像groupby中的sum函數。我不知道這是否可能,只是一個類似於SQL程序的想法。 – LeoCella