Python案例如何用Pandas做数据条件筛选

wen python案例 2

本文目录导读:

Python案例如何用Pandas做数据条件筛选

  1. 准备工作
  2. 基本条件筛选
  3. 使用 isin() 方法
  4. 使用 between() 方法
  5. 使用 query() 方法
  6. 使用 loc 和 iloc
  7. 高级条件筛选
  8. 实际应用案例
  9. 筛选后的操作
  10. 性能优化建议

我来详细介绍Python中Pandas进行数据条件筛选的各种方法。

准备工作

import pandas as pd
import numpy as np
# 创建示例数据
df = pd.DataFrame({
    'A': [1, 2, 3, 4, 5],
    'B': ['a', 'b', 'c', 'd', 'e'],
    'C': [10, 20, 30, 40, 50],
    'D': [True, False, True, False, True]
})
print("原始数据:")
print(df)

基本条件筛选

单条件筛选

# 筛选 A 列大于 3 的数据
result1 = df[df['A'] > 3]
print("A > 3:")
print(result1)
# 筛选 B 列等于 'c' 的数据
result2 = df[df['B'] == 'c']
print("\nB == 'c':")
print(result2)

多条件筛选 (使用 & 和 |)

# 同时满足多个条件 (AND)
result3 = df[(df['A'] > 2) & (df['C'] < 40)]
print("A > 2 AND C < 40:")
print(result3)
# 满足任一条件 (OR)
result4 = df[(df['A'] < 2) | (df['C'] > 40)]
print("\nA < 2 OR C > 40:")
print(result4)
# 使用 ~ 取反 (NOT)
result5 = df[~(df['A'] == 3)]
print("\nNOT A == 3:")
print(result5)

使用 isin() 方法

# 筛选 B 列在列表中的值
result6 = df[df['B'].isin(['a', 'c', 'e'])]
print("B in ['a', 'c', 'e']:")
print(result6)
# 筛选 A 列不在列表中的值
result7 = df[~df['A'].isin([2, 4])]
print("\nA not in [2, 4]:")
print(result7)

使用 between() 方法

# 筛选 C 列在 20 到 40 之间的数据
result8 = df[df['C'].between(20, 40)]
print("C between 20 and 40:")
print(result8)
# 筛选 A 列在 2 到 4 之间(包含边界)
result9 = df[df['A'].between(2, 4, inclusive='both')]
print("\nA between 2 and 4:")
print(result9)

使用 query() 方法

# 使用字符串表达式
result10 = df.query('A > 2 and C < 40')
print("使用 query() 方法:")
print(result10)
# 复杂查询
result11 = df.query('A > 1 and (B == "a" or B == "c")')
print("\n复杂 query:")
print(result11)
# 使用变量
threshold = 30
result12 = df.query('C > @threshold and A < 4')
print("\n使用变量:")
print(result12)

使用 loc 和 iloc

# loc - 标签索引
result13 = df.loc[df['A'] > 3, ['A', 'B']]
print("使用 loc 选择特定列:")
print(result13)
# 多条件 loc
result14 = df.loc[(df['A'] > 2) & (df['D'] == True)]
print("\n多条件 loc:")
print(result14)
# iloc - 位置索引
result15 = df.iloc[1:4, 0:2]  # 行1-3,列0-1
print("\niloc 位置索引:")
print(result15)

高级条件筛选

基于字符串条件

# 创建包含字符串的数据
df_str = pd.DataFrame({
    'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],
    'Email': ['alice@email.com', 'bob@work.com', 'charlie@email.com', 'david@test.com', 'eve@work.com'],
    'Age': [25, 30, 35, 28, 32]
})
# 包含特定字符串
result16 = df_str[df_str['Name'].str.contains('a', case=False)]
print("名字包含 'a':")
print(result16)
# 以特定字符串开头
result17 = df_str[df_str['Email'].str.startswith('a')]
print("\nEmail 以 'a' 开头:")
print(result17)
# 以特定字符串结尾
result18 = df_str[df_str['Email'].str.endswith('email.com')]
print("\nEmail 以 'email.com' ")
print(result18)

基于时间条件

# 创建时间序列数据
dates = pd.date_range('2023-01-01', periods=10, freq='D')
df_time = pd.DataFrame({
    'Date': dates,
    'Value': np.random.randint(1, 100, 10)
})
# 筛选特定日期范围
result19 = df_time[(df_time['Date'] >= '2023-01-03') & 
                   (df_time['Date'] <= '2023-01-06')]
print("日期范围筛选:")
print(result19)
# 筛选月份
result20 = df_time[df_time['Date'].dt.month == 1]
print("\n筛选1月份:")
print(result20)

实际应用案例

# 创建更实际的数据集
students = pd.DataFrame({
    'Name': ['张三', '李四', '王五', '赵六', '钱七', '孙八'],
    'Subject': ['数学', '英语', '数学', '英语', '数学', '英语'],
    'Score': [85, 92, 78, 88, 95, 73],
    'Grade': ['A', 'B', 'C', 'B', 'A', 'C'],
    'Pass': [True, True, True, True, True, False]
})
# 综合条件筛选:数学成绩高于80分且等级为A的学生
high_performers = students[
    (students['Subject'] == '数学') & 
    (students['Score'] > 80) &
    (students['Grade'] == 'A')
]
print("数学成绩优秀的学生:")
print(high_performers)
# 不通过的学生信息
fail_students = students[students['Pass'] == False]
print("\n不及格的学生:")
print(fail_students)
# 使用 loc 修改特定条件的数据
students.loc[students['Score'] < 80, 'Pass'] = False
print("\n更新后的数据:")
print(students)

筛选后的操作

# 筛选并选择特定列
selected = df.loc[df['A'] > 2, ['A', 'C']]
print("筛选并选择特定列:")
print(selected)
# 筛选并重置索引
reset_df = df[df['A'] > 2].reset_index(drop=True)
print("\n筛选后重置索引:")
print(reset_df)
# 链式操作
chain_result = (df[df['A'] > 2]
                .query('C < 40')
                .loc[:, ['A', 'B']])
print("\n链式操作:")
print(chain_result)

性能优化建议

# 对于大数据集,可以使用布尔索引来提高性能
import time
# 创建大数据集
big_df = pd.DataFrame({
    'A': np.random.randint(1, 1000, 1000000),
    'B': np.random.choice(['a', 'b', 'c'], 1000000)
})
# 方法1:直接筛选
start = time.time()
result1 = big_df[big_df['A'] > 500]
print(f"直接筛选耗时: {time.time() - start:.3f}秒")
# 方法2:使用布尔索引
start = time.time()
mask = big_df['A'] > 500
result2 = big_df[mask]
print(f"布尔索引耗时: {time.time() - start:.3f}秒")
# 方法3:使用 query(对于大数据集可能更慢)
# start = time.time()
# result3 = big_df.query('A > 500')
# print(f"query耗时: {time.time() - start:.3f}秒")

Pandas提供了多种灵活的数据筛选方法:

  • 基本条件:使用比较运算符
  • 多条件:使用 &(AND)、(OR)、(NOT)
  • 字符串操作.str.contains().str.startswith()
  • 范围筛选.between().isin()
  • 查询语法.query() 提供更简洁的写法
  • 位置索引.loc[].iloc[]

根据数据量和具体需求选择合适的筛选方法,可以提高代码的可读性和性能。

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