使用 Polars 在闪电般的速度下进行高级聚合和滚动平均
介绍
在本系列的第一部分中,我们已经介绍了 Polars 的基础知识,并将其功能和语法与 Pandas 进行了比较。本部分将进一步提高我们查询的复杂性,因此我们将看到如何执行一些相当复杂的聚合、滚动统计等操作。如果你对 Polars 不熟悉,或者感觉需要复习一下,请务必查看前一部分。否则,让我们继续探索 Polars!
设置
与上一部分类似,请确保克隆/拉取此 GitHub 仓库,因为它包含了本文所需的所有代码。特别是,我们将涵盖此 Notebook,所以如果你想跟着做,请确保获取它。
在此项目中使用的数据可以从 Kaggle 下载(CC0:公共领域)。我假设你已经安装了 Polars,所以只需使用 pip install -U polars
命令来更新到最新版本。
数据处理
读取数据
与上一篇文章类似,让我们读取英国趋势数据集和 category_id
列的映射。
csv_path = './youtube/GBvideos.csv'json_path = './youtube/US_category_id.json'df = pl.read_csv(csv_path)with open(json_path, 'r') as f: categories = json.load(f) id_to_category = {}for c in categories['items']: id_to_category[int(c['id'])] = c['snippet']['title']
清理数据
接下来,让我们解析日期并将类别 ID 映射为类别名称。为了使其更具生产就绪性,我将把日期解析代码放入一个通用的函数中。
def parse_dates(df: pl.DataFrame, date_cols: Dict[str, str]) -> pl.DataFrame: expressions = [] for date_col, format in date_cols.items(): expressions.append(pl.col(date_col).str.to_date(format=format)) df = df.with_columns(expressions) return df# 列名与预期日期格式date_column_format = { "trending_date": '%y.%d.%m', "publish_time"…