超百万行大数据集下按xCordAdjusted与yCordAdjusted坐标分组统计SHOT/MISS/GOAL事件频次的技术需求
嘿,针对你这个百万级数据集的坐标-事件频次统计需求,我给你整理了几种实用的方案,既能高效处理大数据量,又能完美输出你想要的格式:
方案一:用Python Pandas快速实现(适合本地文件)
考虑到你的数据集超过100万行,直接读取可能会内存溢出,所以用分块读取的方式处理,再分组统计频次,最后格式化输出:
import pandas as pd # 分块读取大文件,避免内存不足 chunk_size = 100000 # 可根据你的内存情况调整 chunk_list = [] for chunk in pd.read_csv('your_dataset.csv', sep=' ', header=True, chunksize=chunk_size): # 过滤只保留需要的事件类型,提前减少数据量 filtered_chunk = chunk[chunk['event'].isin(['SHOT', 'MISS', 'GOAL'])] chunk_list.append(filtered_chunk) # 合并所有分块 full_df = pd.concat(chunk_list, axis=0) # 按坐标+事件分组,统计频次 count_result = full_df.groupby(['xCordAdjusted', 'yCordAdjusted', 'event'])['event'] \ .count() \ .rename('total') \ .reset_index() # 按照你要的排序规则(xCord降序,yCord升序)排序 count_result = count_result.sort_values( by=['xCordAdjusted', 'yCordAdjusted'], ascending=[False, True] ) # 格式化输出,处理缩进 prev_x, prev_y = None, None for _, row in count_result.iterrows(): x, y, event, total = row # 给数字添加千位分隔符 formatted_total = f"{total:,}" if x != prev_x or y != prev_y: print(f"{x} {y} {event} {formatted_total}") prev_x, prev_y = x, y else: print(f" {event} {formatted_total}")
方案二:用SQL处理(适合数据库存储的大数据)
如果你的数据已经存在数据库(比如MySQL、PostgreSQL)里,直接用SQL分组查询效率会更高,之后再用简单脚本处理格式:
SQL查询语句
SELECT xCordAdjusted, yCordAdjusted, event, COUNT(*) AS total FROM your_table_name WHERE event IN ('SHOT', 'MISS', 'GOAL') GROUP BY xCordAdjusted, yCordAdjusted, event ORDER BY xCordAdjusted DESC, yCordAdjusted ASC;
格式处理脚本(Python示例)
把查询结果导出为CSV后,用和方案一类似的逻辑处理缩进输出即可。
方案三:用Spark处理超大规模数据(如果百万级还嫌慢)
如果数据集大到Pandas都扛不住,那就用分布式计算框架Spark,处理效率拉满:
from pyspark.sql import SparkSession from pyspark.sql.functions import count # 初始化Spark会话 spark = SparkSession.builder.appName("EventCoordinateCount").getOrCreate() # 读取数据,支持多种数据源 df = spark.read.csv('your_dataset.csv', sep=' ', header=True) # 过滤事件类型、分组统计、排序 count_df = df.filter(df.event.isin(['SHOT', 'MISS', 'GOAL'])) \ .groupBy('xCordAdjusted', 'yCordAdjusted', 'event') \ .agg(count('event').alias('total')) \ .orderBy('xCordAdjusted', ascending=False) \ .orderBy('yCordAdjusted', ascending=True) # 转换为Pandas DataFrame后格式化输出(小数据集结果可行) pandas_result = count_df.toPandas() # 以下同方案一的输出逻辑 prev_x, prev_y = None, None for _, row in pandas_result.iterrows(): x, y, event, total = row formatted_total = f"{total:,}" if x != prev_x or y != prev_y: print(f"{x} {y} {event} {formatted_total}") prev_x, prev_y = x, y else: print(f" {event} {formatted_total}")
内容的提问来源于stack exchange,提问作者jhh19
相关产品推荐
相关产品推荐

