Python案例如何用Pandas做数据过滤函数

wen python案例 1

本文目录导读:

Python案例如何用Pandas做数据过滤函数

  1. 基础过滤函数
  2. 多条件组合过滤
  3. 使用query方法过滤
  4. 基于字符串匹配的过滤
  5. 高级过滤函数
  6. 实际应用案例
  7. 性能优化建议
  8. 使用建议

我来为你详细介绍Pandas数据过滤的各种方法和示例:

基础过滤函数

单条件过滤

import pandas as pd
import numpy as np
# 创建示例数据
df = pd.DataFrame({
    'name': ['张三', '李四', '王五', '赵六', '孙七'],
    'age': [25, 30, 35, 28, 32],
    'salary': [8000, 12000, 15000, 10000, 9000],
    'department': ['技术', '市场', '技术', '财务', '市场'],
    'city': ['北京', '上海', '北京', '广州', '北京']
})
print("原始数据:")
print(df)
print()
# 1. 过滤年龄大于30的员工
def filter_by_age(df, min_age):
    return df[df['age'] > min_age]
print("年龄大于30的员工:")
print(filter_by_age(df, 30))
print()
# 2. 过滤薪资在某个范围
def filter_by_salary_range(df, min_salary, max_salary):
    return df[(df['salary'] >= min_salary) & (df['salary'] <= max_salary)]
print("薪资在10000-15000之间的员工:")
print(filter_by_salary_range(df, 10000, 15000))

多条件组合过滤

# 3. 多条件组合过滤函数
def multiple_condition_filter(df, conditions):
    """
    多条件过滤
    conditions: dict格式的条件
     {'department': '技术', 'age_gt': 30}
    """
    filtered = df.copy()
    for key, value in conditions.items():
        if key.endswith('_gt'):  # 大于
            col = key[:-3]
            filtered = filtered[filtered[col] > value]
        elif key.endswith('_lt'):  # 小于
            col = key[:-3]
            filtered = filtered[filtered[col] < value]
        elif key.endswith('_gte'):  # 大于等于
            col = key[:-4]
            filtered = filtered[filtered[col] >= value]
        elif key.endswith('_lte'):  # 小于等于
            col = key[:-4]
            filtered = filtered[filtered[col] <= value]
        elif key.endswith('_in'):  # 包含列表
            col = key[:-3]
            filtered = filtered[filtered[col].isin(value)]
        else:  # 精确匹配
            filtered = filtered[filtered[key] == value]
    return filtered
# 使用示例
conditions = {
    'department': '技术',
    'salary_gt': 8000,
    'age_lte': 35
}
print("多条件过滤结果:")
print(multiple_condition_filter(df, conditions))

使用query方法过滤

# 4. 使用query方法
def filter_with_query(df, query_string):
    """
    使用query方法进行过滤
    query_string: 如 'age > 30 and salary > 10000'
    """
    return df.query(query_string)
print("使用query过滤 (年龄>25 且 部门='技术'):")
result = filter_with_query(df, "age > 25 and department == '技术'")
print(result)

基于字符串匹配的过滤

# 5. 字符串模糊匹配过滤
def filter_by_string_pattern(df, column, pattern, method='contains'):
    """
    method: 'contains'(包含), 'startswith'(以...开头), 'endswith'(以...
            'regex'(正则表达式)
    """
    if method == 'contains':
        return df[df[column].str.contains(pattern, na=False)]
    elif method == 'startswith':
        return df[df[column].str.startswith(pattern)]
    elif method == 'endswith':
        return df[df[column].str.endswith(pattern)]
    elif method == 'regex':
        return df[df[column].str.match(pattern)]
print("城市包含'北'的员工:")
print(filter_by_string_pattern(df, 'city', '北'))

高级过滤函数

# 6. 通用过滤函数
def advanced_data_filter(df, filter_config):
    """
    高级数据过滤函数
    filter_config: [
        {'column': 'age', 'operator': '>', 'value': 30, 'logic': 'and'},
        {'column': 'department', 'operator': '==', 'value': '技术', 'logic': 'and'},
        {'column': 'salary', 'operator': 'between', 'value': [10000, 20000], 'logic': 'or'}
    ]
    """
    conditions = []
    for config in filter_config:
        col = config['column']
        op = config['operator']
        val = config['value']
        if op == '>':
            condition = df[col] > val
        elif op == '<':
            condition = df[col] < val
        elif op == '>=':
            condition = df[col] >= val
        elif op == '<=':
            condition = df[col] <= val
        elif op == '==':
            condition = df[col] == val
        elif op == '!=':
            condition = df[col] != val
        elif op == 'in':
            condition = df[col].isin(val)
        elif op == 'between':
            condition = (df[col] >= val[0]) & (df[col] <= val[1])
        elif op == 'contains':
            condition = df[col].str.contains(val, na=False)
        else:
            raise ValueError(f"不支持的运算符: {op}")
        conditions.append(condition)
    # 组合条件
    if not conditions:
        return df
    combined_condition = conditions[0]
    for i, condition in enumerate(conditions[1:], 1):
        logic = filter_config[i].get('logic', 'and')
        if logic == 'and':
            combined_condition = combined_condition & condition
        elif logic == 'or':
            combined_condition = combined_condition | condition
    return df[combined_condition]
# 使用示例
filter_config = [
    {'column': 'age', 'operator': '>=', 'value': 25, 'logic': 'and'},
    {'column': 'salary', 'operator': 'between', 'value': [8000, 15000], 'logic': 'and'},
    {'column': 'department', 'operator': 'in', 'value': ['技术', '市场'], 'logic': 'and'}
]
result = advanced_data_filter(df, filter_config)
print("高级过滤结果:")
print(result)

实际应用案例

# 7. 数据分析中的实际应用
# 创建更复杂的数据集
sales_data = pd.DataFrame({
    'date': pd.date_range('2023-01-01', periods=100),
    'product': np.random.choice(['A', 'B', 'C'], 100),
    'sales': np.random.randint(100, 1000, 100),
    'quantity': np.random.randint(1, 20, 100),
    'region': np.random.choice(['华东', '华南', '华北'], 100)
})
def analyze_sales_by_region(df, region, min_sales=500):
    """
    分析特定区域的销售数据
    """
    # 过滤数据
    filtered = df[
        (df['region'] == region) & 
        (df['sales'] > min_sales)
    ]
    # 返回统计信息
    return {
        'total_sales': filtered['sales'].sum(),
        'avg_sales': filtered['sales'].mean(),
        'total_quantity': filtered['quantity'].sum(),
        'product_distribution': filtered['product'].value_counts()
    }
# 使用案例
result = analyze_sales_by_region(sales_data, '华东', min_sales=300)
print(f"华东区销售分析:")
print(f"总销售额: {result['total_sales']}")
print(f"平均销售额: {result['avg_sales']:.2f}")
print(f"总销量: {result['total_quantity']}")
print("产品销售分布:")
print(result['product_distribution'])

性能优化建议

# 8. 大数据量时的优化过滤
def optimized_filter(df, conditions):
    """
    大数据量时的优化过滤
    """
    # 使用布尔索引而不是loc
    mask = pd.Series(True, index=df.index)
    for col, op, val in conditions:
        if op == '==':
            mask &= (df[col] == val)
        elif op == '>':
            mask &= (df[col] > val)
        # ... 其他运算符
    return df[mask]
# 使用numpy条件加速
def numpy_optimized_filter(df, column, threshold):
    """
    使用numpy加速过滤
    """
    values = df[column].values  # 转换为numpy数组
    mask = values > threshold
    return df[mask]

使用建议

  1. 选择合适的方法

    • 简单条件 .loc
    • 复杂条件用 query()
    • 动态条件用函数封装
  2. 性能考虑

    • 大数据量使用 .loc
    • 避免链式索引
    • 使用 isin() 替代多个
  3. 代码可维护性

    • 将过滤逻辑封装成函数
    • 使用配置化的方式定义过滤规则
    • 添加适当的注释和文档

这些示例覆盖了Pandas数据过滤的主要场景,你可以根据实际需求选择合适的实现方式。

抱歉,评论功能暂时关闭!