2017-01-11 18 views
1

指數分組日期,我想在下面的格式轉換日期的列表:可以用Python

01-02-12 
01-03-12 
01-27-12 
02-01-12 
02-23-12 
    . 
    . 
    . 
01-03-13 
02-02-13 

1 
1 
1 
2 
2 
. 
. 
. 
13 
14 

即:指數每個日期按月,相對於一年也。

我不知道該怎麼做,也找不到類似的問題,所以建議不勝感激。 35~~~~~~~~~~~~~~~~~~~~~~~~~ 編輯: 回覆@Psidom。 只是一個數字組成的數據集。在我正在處理的實際數據集中,我將日期轉換爲日期時間對象。

dat = pd.read_csv('matchdata-update.csv',encoding = "ISO-8859-1") 
dat['Date']=pd.to_datetime(dat['Date'],format='%m-%d-%y% I:%M%p'). 

理想情況下,我希望它數一個月,即使它沒有被觀察到。 最終目標是對每個月進行索引並對該insex中的行數進行計數,因此如果沒有觀察到月份,則該索引的行數將僅爲0.

+1

所以一年總是從12開始?如果有一個月失蹤了幾個月,你如何計算下一年,還是從13歲開始還是更小一些?這是一個字符串或日期時間對象的列表? – Psidom

+0

http://stackoverflow.com/questions/4039879/best-way-to-find-the-months-between-two-dates – DaveQ

回答

1

如果要計算每個月行,這應該工作:

dat.set_index("Date").resample("M").size() 
+1

出色的工作。我承諾,一旦我更加努力,就會開始回報我的青睞。 – Luke

+0

好聽。但是你不必感到有責任心,一個好的問題可以讓其他有相同問題的人受益。 – Psidom

1

下面是使用數據視爲給定的生產要求的答案,包括0失蹤monthes不同的答案。

dates = '''\ 
01-02-12 
01-03-12 
01-27-12 
02-01-12 
02-23-12 
01-03-13 
02-02-13 
'''.splitlines() 

def monthnum(date, baseyear): 
    "Convert date as 'mm-dd-yy' to month number starting with baseyear xx." 
    m,d,y = map(int, date.split('-')) 
    return m + 12 * (y-baseyear) 

print(monthnum(dates[0], 12) == 1, monthnum(dates[-1], 12) == 14) 

def monthnums(dates, baseyear): 
    "Yield month numbers of 'mm-dd-yy' starting with baseyear." 
    for date in dates: 
     m,d,y = map(int, date.split('-')) 
     yield m + 12 * (y-baseyear) 

print(list(monthnums(dates, 12)) == [1,1,1,2,2,13,14]) 

def num_per_month(mnums): 
    prev, n = 1, 0 
    for k in mnums: 
     if k == prev: 
      n += 1 
     else: 
      yield prev, n 
      for i in range(prev+1, k): 
       yield i, 0 
      prev, n = k, 1 
    yield prev, n 

for m, n in num_per_month(monthnums(dates, 12)): 
    print(m, n) 

打印

True True 
True 
1 3 
2 2 
3 0 
4 0 
5 0 
6 0 
7 0 
8 0 
9 0 
10 0 
11 0 
12 0 
13 1 
14 1