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

按日期分组统计DataFrame中分类变量Va、Vb的每日数量

问题描述

原始数据

DateTimeVaVb
01-01-202305:55AB
01-01-202306:25A
01-01-202317:42B
01-01-202319:17AB
02-01-202305:55AB
02-01-202306:25AB
02-01-202317:42AB
02-01-202319:17A

需求

按Date列分组,统计每个日期下Va和Vb列的非空值数量。

实现代码

使用Pandas可快速完成需求,核心逻辑是按日期分组后,对目标列调用count()方法(该方法默认统计非空值数量):

import pandas as pd

# 构造原始DataFrame
data = {
    'Date': ['01-01-2023', '01-01-2023', '01-01-2023', '01-01-2023',
             '02-01-2023', '02-01-2023', '02-01-2023', '02-01-2023'],
    'Time': ['05:55', '06:25', '17:42', '19:17', '05:55', '06:25', '17:42', '19:17'],
    'Va': ['A', 'A', '', 'A', 'A', 'A', 'A', 'A'],
    'Vb': ['B', '', 'B', 'B', 'B', 'B', 'B', '']
}

df = pd.DataFrame(data)
# 若原始空值为字符串,先转为Pandas标准空值类型
df[['Va', 'Vb']] = df[['Va', 'Vb']].replace('', pd.NA)

# 分组统计非空值
result = df.groupby('Date')[['Va', 'Vb']].count()
print(result)

预期结果

DateVaVb
01-01-202333
02-01-202343

内容的提问来源于stack exchange,提问作者Himadri Shekhar Bhatta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 21:55:42