本文目录导读:

我来详细讲解如何使用Pandas进行数据索引和切片操作,包含丰富的案例。
基础准备
import pandas as pd
import numpy as np
# 创建示例数据
data = {
'姓名': ['张三', '李四', '王五', '赵六', '钱七', '孙八'],
'年龄': [25, 30, 35, 28, 32, 27],
'城市': ['北京', '上海', '广州', '深圳', '北京', '上海'],
'薪资': [15000, 20000, 25000, 18000, 22000, 16000],
'部门': ['技术', '市场', '技术', '销售', '市场', '技术']
}
df = pd.DataFrame(data)
print("原始数据:")
print(df)
列索引切片
# 选择单列
print("选择单列:")
print(df['姓名'])
print("-" * 30)
# 选择多列
print("选择多列:")
print(df[['姓名', '年龄', '薪资']])
print("-" * 30)
# 选择列范围(使用列名切片)
print("列范围切片:")
print(df.loc[:, '姓名':'城市'])
行索引切片
# 使用iloc进行整数位置索引
print("使用iloc选择前3行:")
print(df.iloc[0:3])
print("-" * 30)
# 使用loc进行标签索引
print("使用loc选择特定行:")
print(df.loc[0:3]) # 注意:loc包含结束位置
print("-" * 30)
# 选择特定行
print("选择第1、3、5行:")
print(df.iloc[[0, 2, 4]])
条件索引
# 单条件筛选
print("年龄大于30的人员:")
print(df[df['年龄'] > 30])
print("-" * 30)
# 多条件筛选(使用&)
print("北京且薪资>20000:")
print(df[(df['城市'] == '北京') & (df['薪资'] > 20000)])
print("-" * 30)
# 多条件筛选(使用|)
print("北京或上海的人员:")
print(df[(df['城市'] == '北京') | (df['城市'] == '上海')])
# 使用isin()方法
print("\n技术或市场部门:")
print(df[df['部门'].isin(['技术', '市场'])])
综合索引切片案例
# 案例1:数据透视
print("案例1 - 选择技术和市场部门的人员信息:")
tech_market = df[(df['部门'].isin(['技术', '市场'])) & (df['薪资'] > 18000)]
print(tech_market[['姓名', '部门', '薪资']])
print("-" * 40)
# 案例2:按条件修改数据
print("案例2 - 给薪资低于20000的人员加薪10%:")
df_copy = df.copy()
df_copy.loc[df_copy['薪资'] < 20000, '薪资'] = df_copy['薪资'] * 1.1
print(df_copy)
print("-" * 40)
# 案例3:分组统计
print("案例3 - 各部门薪资统计:")
dept_stats = df.groupby('部门')['薪资'].agg(['mean', 'max', 'min', 'count'])
print(dept_stats)
高级索引技巧
# 创建多级索引
arrays = [['A', 'A', 'B', 'B', 'C', 'C'],
['2023', '2024', '2023', '2024', '2023', '2024']]
multi_index = pd.MultiIndex.from_arrays(arrays, names=['组别', '年份'])
multi_df = pd.DataFrame({'数值': [100, 200, 150, 250, 120, 180]}, index=multi_index)
print("多级索引数据:")
print(multi_df)
print("-" * 30)
# 多级索引切片
print("选择A组数据:")
print(multi_df.loc['A'])
print("-" * 30)
print("选择2024年数据:")
print(multi_df.xs('2024', level='年份'))
实际应用案例
# 股票数据分析案例
import pandas as pd
import numpy as np
# 创建股票数据
dates = pd.date_range('2024-01-01', periods=100, freq='D')
stock_data = pd.DataFrame({
'日期': dates,
'开盘价': np.random.uniform(100, 200, 100),
'收盘价': np.random.uniform(100, 200, 100),
'成交量': np.random.randint(10000, 100000, 100)
})
print("股票数据前5行:")
print(stock_data.head())
# 实际应用:分析特定时段的数据
print("\n2024年1月数据:")
january_data = stock_data[
(stock_data['日期'] >= '2024-01-01') &
(stock_data['日期'] <= '2024-01-31')
]
print(january_data)
# 条件筛选:成交量大的交易日
print("\n成交量大于平均值的交易日:")
avg_volume = stock_data['成交量'].mean()
high_volume_days = stock_data[stock_data['成交量'] > avg_volume]
print(high_volume_days[['日期', '成交量']].head())
性能优化建议
# 设置索引提高查询效率
print("设置姓名列为索引:")
df_indexed = df.set_index('姓名')
print(df_indexed)
print("-" * 30)
# 使用索引快速定位
print("快速查找张三的信息:")
print(df_indexed.loc['张三'])
print("-" * 30)
# 批量查询
print("批量查询多个人员:")
print(df_indexed.loc[['张三', '李四', '王五']])
常见问题和解决方案
# 处理缺失值时的索引
df_with_nan = df.copy()
df_with_nan.loc[2, '薪资'] = np.nan
print("含缺失值数据:")
print(df_with_nan)
# 使用dropna()清理后索引
print("\n清理缺失值后:")
clean_df = df_with_nan.dropna()
print(clean_df)
# 填充缺失值
print("\n填充缺失值后:")
filled_df = df_with_nan.fillna({'薪资': df_with_nan['薪资'].mean()})
print(filled_df)
# 重置索引
print("\n重置索引:")
reset_df = filled_df.reset_index(drop=True)
print(reset_df)
Pandas的索引切片核心要点:
- loc:基于标签的索引
- iloc:基于位置的索引
- 布尔索引:条件筛选
- 链式操作:组合多个条件
这些操作在数据清洗、分析和预处理中非常实用,掌握好这些技能能大大提高数据处理效率。