You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas分组统计日期行数并关联GDP、失业率字段的实现方法

问题

给定如下Pandas DataFrame:

import pandas as pd
from datetime import datetime

df = pd.DataFrame({
    'loan_id': [1,2,3,4,5,6,7],
    'gdp': [1.1, 1.2, 1.3, 1.4, 1.1, 1.2, 1.3],
    'unempl': [3.1, 3.2, 3.3, 3.4, 3.1, 3.2, 3.3],
    'the_date': [datetime(2020,1,1),datetime(2020,1,2),datetime(2020,1,3),datetime(2020,1,4),
                datetime(2020,1,1),datetime(2020,1,2),datetime(2020,1,3)]
})

数据预览:

loan_idgdpunemplthe_date
011.13.12020-01-01
121.23.22020-01-02
231.33.32020-01-03
341.43.42020-01-04
451.13.12020-01-01
561.23.22020-01-02
671.33.32020-01-03

需要实现两个需求:

  • 统计每个日期对应的行数
  • 同时保留对应日期的gdp和unempl字段

最终目标DataFrame:

the_date    gdp   unempl   count
2020-01-01  1.1   3.1      2
2020-01-02  1.2   3.2      2
2020-01-03  1.3   3.3      2  
2020-01-04  1.4   3.4      1

目前已通过以下代码实现日期行数统计,但无法关联gdp和unempl字段:

df2 = df.groupby('the_date')['the_date'].count()

输出结果:

the_date
2020-01-01    2
2020-01-02    2
2020-01-03    2
2020-01-04    1
Name: the_date, dtype: int64
解决方法

由于同一日期对应的gdp和unempl值是唯一的,可通过以下几种方式实现需求:

方法1:多字段聚合

使用groupby配合agg(),为不同字段指定对应聚合逻辑,一次完成取值与计数:

result = df.groupby('the_date').agg(
    gdp=('gdp', 'first'),  # 取该日期下任意一个gdp值(所有值一致)
    unempl=('unempl', 'first'),  # 同理取unempl值
    count=('loan_id', 'count')  # 统计行数,用任意非空字段均可
).reset_index()

方法2:分步骤合并

先提取日期与gdp、unempl的唯一映射,再和计数结果合并:

# 获取日期与属性的唯一对应关系
date_attrs = df[['the_date', 'gdp', 'unempl']].drop_duplicates()
# 统计每个日期的行数
date_counts = df.groupby('the_date').size().reset_index(name='count')
# 合并两个结果
result = pd.merge(date_attrs, date_counts, on='the_date')

方法3:添加计数列后去重

先给原数据添加每个日期的计数列,再去重保留唯一日期的记录:

df['count'] = df.groupby('the_date')['loan_id'].transform('count')
result = df[['the_date', 'gdp', 'unempl', 'count']].drop_duplicates()

以上三种方法均可得到目标DataFrame,输出示例:

the_date  gdp  unempl  count
0 2020-01-01  1.1     3.1      2
1 2020-01-02  1.2     3.2      2
2 2020-01-03  1.3     3.3      2
3 2020-01-04  1.4     3.4      1

内容的提问来源于stack exchange,提问作者ps0604

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 21:05:22