Polars 筛选教程
最后修改时间:2025年3月1日
Polars 是一个快速高效的 Python DataFrame 库。它专为高性能数据处理和分析而设计。筛选是数据分析中的一项常用操作,它允许您根据条件提取特定行。
本教程介绍了如何在 Polars DataFrame 中筛选数据。我们将通过实际示例探讨基本和高级的筛选技术。
基本筛选
Polars 中的筛选是通过 filter
方法完成的。此方法接受一个条件,并返回一个满足该条件的新 DataFrame。
import polars as pl data = { 'Name': ['Alice', 'Bob', 'Charlie', 'David'], 'Age': [25, 30, 35, 40], 'City': ['New York', 'Los Angeles', 'Chicago', 'Houston'] } df = pl.DataFrame(data) filtered_df = df.filter(pl.col('Age') > 30) print(filtered_df)
filter(pl.col('Age') > 30)
会筛选出 'Age' 列大于 30 的行。这对于提取特定数据子集非常有用。
多个条件
您可以使用逻辑运算符(如 &
(AND)和 |
(OR))组合多个条件。这允许进行更复杂的筛选。
import polars as pl data = { 'Name': ['Alice', 'Bob', 'Charlie', 'David'], 'Age': [25, 30, 35, 40], 'City': ['New York', 'Los Angeles', 'Chicago', 'Houston'] } df = pl.DataFrame(data) filtered_df = df.filter((pl.col('Age') > 30) & (pl.col('City') == 'Chicago')) print(filtered_df)
(pl.col('Age') > 30) & (pl.col('City') == 'Chicago')
会筛选出 'Age' 大于 30 且 'City' 为 'Chicago' 的行。这对于精确数据提取非常有用。
使用字符串操作进行筛选
Polars 支持用于筛选的字符串操作。您可以使用 str.contains
等方法根据字符串模式筛选行。
import polars as pl data = { 'Name': ['Alice', 'Bob', 'Charlie', 'David'], 'Age': [25, 30, 35, 40], 'City': ['New York', 'Los Angeles', 'Chicago', 'Houston'] } df = pl.DataFrame(data) filtered_df = df.filter(pl.col('City').str.contains('New')) print(filtered_df)
str.contains('New')
会筛选出 'City' 列包含子字符串 'New' 的行。这对于基于模式的筛选非常有用。
使用 Null 值进行筛选
Polars 提供了在筛选过程中处理 Null 值的方法。您可以使用 is_null
和 is_not_null
来筛选包含 Null 值或非 Null 值的行。
import polars as pl data = { 'Name': ['Alice', 'Bob', 'Charlie', 'David'], 'Age': [25, None, 35, 40], 'City': ['New York', 'Los Angeles', None, 'Houston'] } df = pl.DataFrame(data) filtered_df = df.filter(pl.col('Age').is_not_null()) print(filtered_df)
is_not_null
会筛选出 'Age' 列不为 Null 的行。这对于清理包含缺失值的数据非常有用。
使用自定义函数进行筛选
您可以应用自定义函数来筛选行。这允许进行灵活且复杂的筛选逻辑。
import polars as pl data = { 'Name': ['Alice', 'Bob', 'Charlie', 'David'], 'Age': [25, 30, 35, 40], 'City': ['New York', 'Los Angeles', 'Chicago', 'Houston'] } df = pl.DataFrame(data) def custom_filter(age): return age > 30 and age < 40 filtered_df = df.filter(pl.col('Age').apply(custom_filter)) print(filtered_df)
apply(custom_filter)
会应用一个自定义函数来筛选 'Age' 在 30 到 40 之间的行。这对于高级筛选非常有用。
筛选的最佳实践
- 理解数据:在应用筛选之前,请分析数据结构。
- 使用高效的条件:为提高性能优化条件。
- 处理 Null 值:使用
is_null
和is_not_null
来处理 Null 值。 - 验证结果:检查筛选后的数据是否准确和一致。
来源
在本文中,我们探讨了如何在 Polars DataFrame 中筛选数据。
作者
所有 Polars 教程列表。