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

如何按county统计实例数量并关联至单county单行数据表

统计各County事故记录数量的通用方案

下面是几种主流工具的实现方式,覆盖数据库、Python、R场景,都是通用的统计方案:

SQL 数据库实现

不管用MySQL、PostgreSQL还是SQL Server,都可以用这个语句生成每个county一行的统计表:

SELECT county, COUNT(*) AS accident_count
FROM accident_records
GROUP BY county;
  • GROUP BY county 将同属一个county的记录归为一组
  • COUNT(*) 统计每组内的记录总数,别名accident_count就是该county的事故实例数

如果需要给原表的每条记录都添加上对应county的总事故数,可以用窗口函数:

SELECT *,
       COUNT(*) OVER (PARTITION BY county) AS county_total_accidents
FROM accident_records;

Python Pandas 实现

处理本地数据集时常用的方案:

import pandas as pd

# 假设你的数据存储在DataFrame df中
county_stats = df.groupby('county').size().reset_index(name='accident_count')
  • groupby('county') 按county分组
  • size() 统计每组的记录数
  • reset_index() 将分组索引转为普通列,name参数指定统计列的名称

要是想给原表的每条记录追加对应county的统计值:

df['county_accident_count'] = df.groupby('county')['county'].transform('count')

R 语言实现

用dplyr包可以快速实现:

library(dplyr)

# 生成每个county一行的统计数据表
county_stats <- accident_records %>%
  group_by(county) %>%
  summarise(accident_count = n(), .groups = 'drop')
  • group_by(county) 按county分组
  • summarise(n()) 统计每组的记录数
  • .groups = 'drop' 取消分组状态,得到标准的二维数据表

给原表添加对应county的统计值:

accident_records <- accident_records %>%
  group_by(county) %>%
  mutate(county_accident_count = n()) %>%
  ungroup()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 12:23:14