【问题标题】:Python Pandas GroupBy: calculating age by subtracting date from the last 10 yearsPython Pandas GroupBy:通过从过去 10 年中减去日期来计算年龄
【发布时间】:2020-05-28 23:41:06
【问题描述】:

我的数据框如下所示:

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    

现在我想为每个 ID 创建过去 10 年的平均年龄列(使用 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 年的年龄值。谁能帮我解决这个问题?

【问题讨论】:

  • 为什么 DV 的年龄在 2015-16 之间减少了?是错字吗?

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


【解决方案1】:

为什么不得到一个像df['Year'] = pd.to_datetime(df['Date']).dt.year 这样的年份列,然后在['ID','Year'] 上做一个groupby 就像:

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

输出:

完成后pd.pivot_table 应该允许您将年份放入列中。

【讨论】:

  • 如何计算ID最近10年的年龄问题。你提到的方式不计算年龄。它只生成年份列,而不是年龄列
  • 你能粘贴你的实际数据吗?我可以玩它并发布实际代码。但是,您似乎已经有了计算年龄的代码?
  • ID 日期 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
  • 谢谢。当您计算年龄时,您从今天减去日期,这对于计算 2020 年是正确的。如果您再次阅读我的帖子,我还想计算过去 10 年(即 2020、2019、2018、2017、2016、2015 ,2014,2013,2012,2011)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-06
  • 2021-06-26
  • 1970-01-01
  • 2021-04-22
  • 1970-01-01
  • 2018-11-04
  • 1970-01-01
相关资源
最近更新 更多