Python案例如何用Pandas做数据索引选择

wen python案例 2

本文目录导读:

Python案例如何用Pandas做数据索引选择

  1. 基础数据准备
  2. 基础索引方法
  3. 高级索引技巧
  4. 实战案例
  5. 性能优化技巧
  6. 常见问题处理
  7. 索引选择速查表

我来详细介绍使用Pandas进行数据索引选择的多种方法,从基础到进阶。

基础数据准备

import pandas as pd
import numpy as np
# 创建示例数据
df = pd.DataFrame({
    '姓名': ['张三', '李四', '王五', '赵六', '钱七'],
    '年龄': [25, 30, 35, 28, 32],
    '城市': ['北京', '上海', '广州', '深圳', '北京'],
    '薪资': [15000, 20000, 18000, 22000, 16000],
    '部门': ['技术', '市场', '技术', '财务', '技术']
})
print("原始数据:")
print(df)

基础索引方法

1 loc - 基于标签的索引

# 选择单行
print("选择第2行:")
print(df.loc[1])
# 选择多行
print("\n选择第1-3行:")
print(df.loc[0:2])
# 选择特定列
print("\n选择姓名和年龄列:")
print(df.loc[:, ['姓名', '年龄']])
# 条件选择
print("\n选择年龄大于30的员工:")
print(df.loc[df['年龄'] > 30, ['姓名', '年龄', '薪资']])
# 布尔索引
print("\n选择北京的技术人员:")
print(df.loc[(df['城市'] == '北京') & (df['部门'] == '技术')])

2 iloc - 基于位置的索引

# 选择第一行
print("选择第一行:")
print(df.iloc[0])
# 选择前3行
print("\n选择前3行:")
print(df.iloc[:3])
# 选择特定位置的单元格
print("\n选择第2行第3列:")
print(df.iloc[1, 2])
# 选择特定行列
print("\n选择第1-3行,第1-3列:")
print(df.iloc[0:3, 0:3])
# 使用列表选择
print("\n选择第0、2、4行:")
print(df.iloc[[0, 2, 4]])

高级索引技巧

1 多级索引 (MultiIndex)

# 创建多级索引数据
arrays = [
    ['北京', '北京', '上海', '上海', '广州'],
    ['技术', '市场', '技术', '市场', '技术']
]
index = pd.MultiIndex.from_arrays(arrays, names=['城市', '部门'])
multi_df = pd.DataFrame({
    '销售额': [100, 150, 120, 180, 90],
    '利润': [20, 30, 25, 35, 18]
}, index=index)
print("多级索引数据:")
print(multi_df)
# 选择特定层级
print("\n选择北京的数据:")
print(multi_df.loc['北京'])
# 选择特定组合
print("\n选择北京技术部门:")
print(multi_df.loc[('北京', '技术')])
# 使用xs选择
print("\n选择所有技术部门:")
print(multi_df.xs('技术', level='部门'))

2 条件组合索引

# 复杂条件选择
high_salary = df[df['薪资'] > 17000]
tech_dept = df[df['部门'] == '技术']
print("高薪技术人员:")
print(high_salary[high_salary['部门'] == '技术'])
# 使用query方法
print("\n使用query查询:")
print(df.query('薪资 > 17000 and 部门 == "技术"'))
# 使用isin
print("\n选择北京或上海的员工:")
print(df[df['城市'].isin(['北京', '上海'])])

实战案例

案例1:数据分析筛选

# 创建更大规模的数据
np.random.seed(42)
sales_data = pd.DataFrame({
    '日期': pd.date_range('2024-01-01', periods=100, freq='D'),
    '产品': np.random.choice(['A', 'B', 'C'], 100),
    '销售额': np.random.randint(1000, 10000, 100),
    '数量': np.random.randint(10, 100, 100),
    '门店': np.random.choice(['东区', '西区', '南区', '北区'], 100)
})
# 选择特定时间段
print("2024年1月的数据:")
jan_data = sales_data[
    (sales_data['日期'] >= '2024-01-01') & 
    (sales_data['日期'] <= '2024-01-31')
]
print(jan_data.head())
# 选择高销售额的产品A
print("\n产品A高销售额记录:")
high_sales_A = sales_data[
    (sales_data['产品'] == 'A') & 
    (sales_data['销售额'] > 5000)
]
print(high_sales_A.head())
# 按门店分组统计
print("\n各门店销售额统计:")
store_stats = sales_data.groupby('门店').agg({
    '销售额': ['sum', 'mean', 'max'],
    '数量': 'sum'
})
print(store_stats)

案例2:金融数据处理

# 创建股票数据
dates = pd.date_range('2024-01-01', periods=50, freq='D')
stock_data = pd.DataFrame({
    '日期': dates,
    '开盘价': np.random.uniform(100, 110, 50),
    '收盘价': np.random.uniform(100, 110, 50),
    '成交量': np.random.randint(10000, 100000, 50)
})
# 设置日期为索引
stock_data.set_index('日期', inplace=True)
# 选择特定日期范围
print("1月中旬的数据:")
mid_jan = stock_data.loc['2024-01-10':'2024-01-20']
print(mid_jan)
# 条件选择(涨幅超过2%)
stock_data['涨跌幅'] = (stock_data['收盘价'] - stock_data['开盘价']) / stock_data['开盘价']
print("\n涨幅超过2%的交易日:")
big_gain = stock_data[stock_data['涨跌幅'] > 0.02]
print(big_gain[['开盘价', '收盘价', '涨跌幅']])
# 成交量排名前5的交易日
print("\n成交量最大的5天:")
top_volume = stock_data.nlargest(5, '成交量')
print(top_volume)

性能优化技巧

import time
# 创建大数据集
large_df = pd.DataFrame({
    'A': range(1000000),
    'B': np.random.randn(1000000),
    'C': np.random.choice(['X', 'Y', 'Z'], 1000000)
})
# 比较不同索引方法的性能
start = time.time()
result1 = large_df[large_df['A'] > 500000]
print(f"直接布尔索引: {time.time() - start:.4f}秒")
start = time.time()
large_df2 = large_df.set_index('A')
result2 = large_df2.loc[500000:]
print(f"使用索引: {time.time() - start:.4f}秒")
# 使用query优化
start = time.time()
result3 = large_df.query('A > 500000 and B > 0')
print(f"使用query: {time.time() - start:.4f}秒")

常见问题处理

# 处理缺失值
df_with_nan = df.copy()
df_with_nan.loc[2:4, '薪资'] = np.nan
print("包含缺失值的数据:")
print(df_with_nan)
# 选择非空值
print("\n薪资不为空的记录:")
print(df_with_nan[df_with_nan['薪资'].notna()])
# 处理重复索引
df_duplicate = pd.concat([df, df.iloc[0:2]])
print("\n包含重复索引的数据:")
print(df_duplicate)
# 删除重复行
print("\n删除重复行:")
print(df_duplicate.drop_duplicates())

索引选择速查表

方法 用途 示例
loc[] 标签索引 df.loc['a':'c']
iloc[] 位置索引 df.iloc[0:3]
列选择 df['列名']
query() 查询语法 df.query('a > 1')
filter() 模式匹配 df.filter(like='name')

这些技巧在日常数据处理中非常实用,建议根据实际需求选择最合适的索引方法。

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