Python Pandas GroupBy:通过从最近10年中减去日期来计算年龄

时间:2020-05-28 23:41:06

标签: python python-3.x pandas pandas-groupby

我有一个如下所示的数据框:

df:

   ID             DATE  
     KV          26/09/1969 0:00:00         
     KV          27/05/1970 0:00:00         
     KV          17/01/1989 0:00:00        
     KV          27/05/1970 0:00:00        
     DV          24/07/1984 0:00:00         
     DV          11/03/2015 0:00:00        
     DV           4/12/2015 0:00:00         
     GV          26/10/2005 0:00:00         
     GV          11/10/2017 0:00:00         
     GV          11/10/2017 0:00:00    

现在,我想为最近10年的每个ID(使用groupby)创建一个平均年龄列。

所需的输出:

Average Age
ID  2020    2019    2018    2017    2016    2015    2014    2013    2012    2011
KV  45.5    44.5    43.5    42.5    41.5    40.5    39.5    38.5    37.5    36.5
DV  15.3    14.3    13.3    12.3    11.3    31       30      29      28      27
GV  3        2       1       0      0        0      0         0       0       0           

可以通过从日期列中减去最近10年来计算年龄。我使用以下命令来计算2020年的年龄:

df.groupby('ID')['Date'].agg(lambda x:pd.datetime('01-04-2020')-x['Date']) 

但是,我无法通过一个命令弄清楚如何计算最近10年的年龄值。谁能帮我解决这个问题?

1 个答案:

答案 0 :(得分:0)

为什么不获得像df['Year'] = pd.to_datetime(df['Date']).dt.year这样的年份列,然后像这样对groupby都做['ID','Year']

import pandas as pd

def parse_date(td):
    ### no leap-year in account
    resYear = float(td.days)/365.0                   
    resMonth = int((resYear - int(resYear))*365/30) 
    resYear = int(resYear)
    return str(resYear) + "Y" + str(resMonth) + "m"

df = pd.DataFrame([['KV','26/09/1969 0:00:00'],['KV','26/09/1979 0:00:00'],['KV','26/09/1989 0:00:00'],['DV','26/09/1984 0:00:00'],['GV','26/09/2014 0:00:00']],columns=['id','date'])
df['date'] = pd.to_datetime(df['date'])
df['year'] = df['date'].dt.year
df['age'] = df.groupby(['id','year'])['date'].apply(lambda x:pd.to_datetime('today')-x).reset_index()['date'].apply(parse_date)
df

输出:

enter image description here

一旦完成pd.pivot_table,您就可以在列中输入年份。