基于年份和特定条件的分组计数 [英] Groupby count based on year and specific condition

查看:54
本文介绍了基于年份和特定条件的分组计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a dataframe as shown below

Tenancy_ID        Unit_ID        Tenancy_End_Date
1                 A              2012-09-06 11:34:15
2                 B              2013-09-08 10:35:18
3                 A              2014-09-06 11:34:15
4                 C              2014-09-06 11:34:15
5                 B              2015-09-06 11:34:15
6                 A              2014-09-06 11:34:15
5                 A              2015-09-06 11:34:15
7                 A              2019-09-06 11:34:15
4                 C              2014-01-06 11:34:15
5                 C              2014-05-06 11:34:15

从上面我想生成下面的数据框

From the above I would like to generate below dataframe

预期输出:

Unit_ID    NoC_2012   NoC_2013  NoC_2014   NoC_2015   NoC_2016   NoC_2017  NoC_2018   NoC_2019
A          1          0         2          1          0          0         0          1
B          0          1         0          1          0          0         0          0
C          0          0         3          0          0          0         0          0

其中 NoC = 合同数量.

Where NoC = Number of Contracts.

例如 NoC_2012 = 基于 Tenancy_End_Date 的 2012 年合同数量

For example NoC_2012 = Number of Contracts in year 2012 based on Tenancy_End_Date

注意:Tenancy_ID 不是唯一的.Tenancy_ID 和 Unit_ID 是唯一的.即有相同的 Tenancy_ID 和不同的 Unit_ID.

Note: Tenancy_ID is not unique. Tenancy_ID with Unit_ID is unique. ie there are same Tenancy_ID with different Unit_ID.

推荐答案

首先将您的列转换为日期时间:

df['Tenancy_End_Date']= pd.to_datetime(df['Tenancy_End_Date'])

然后使用 DataFrame.pivot_tableSeries.dt.year 获取年份:

new_df = (df.assign(Year  = df['Tenancy_End_Date'].dt.year)
           #if you don't want convert to datetime use this instead
           #.assign(Year  = pd.to_datetime(df['Tenancy_End_Date']).dt.year)
            .pivot_table(index = 'Unit_ID',
                         columns = 'Year',
                         values = 'Tenancy_ID'
                         ,aggfunc = 'count',
                         fill_value =0)
            .add_prefix('NoC_')
            .reset_index()
            .rename_axis(columns = None))
print(new_df)
  Unit_ID  NoC_2012  NoC_2013  NoC_2014  NoC_2015  NoC_2019
0       A         1         0         2         1         1
1       B         0         1         0         1         0
2       C         0         0         3         0         0

这篇关于基于年份和特定条件的分组计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆