python 数据分析处理库-Pandas - col'
1.1 Pandas概述
核心概念:
Pandas 是基于 NumPy 的数据分析库,核心数据结构:Series(一维)和 DataFrame(二维)。 应用场景:数据清洗、转换、统计分析、时间序列处理。 特点:
支持异构数据、缺失值处理、灵活的数据对齐。
1.2 Pandas基本操作
数据读写: df = pd.read_csv('data.csv') # 读取 CSV
df.to_excel('output.xlsx') # 写入 Excel 数据查看: df.head(5) # 前5行
df.info() # 数据结构
df.describe() # 统计摘要 数据选取: df['column'] # 单列
df[['col1', 'col2']] # 多列
1.3 Pandas索引
索引类型:
行索引:df.index(默认 RangeIndex) 列索引:df.columns 设置索引: df.set_index('date', inplace=True) # 指定列为索引
df.reset_index() # 重置索引 多层索引(MultiIndex): df = df.set_index(['year', 'month']) # 分层索引
1.4 groupby操作
基础分组聚合: df.groupby('category')['price'].mean() # 按类别分组计算均价 多级分组: df.groupby(['year', 'month']).sum() 自定义聚合函数: def range_agg(x):
return x.max() - x.min()
df.groupby('group').agg(range_agg)
1.5-1.7 数值运算与对象操作
数值运算: df['col'].sum() / df['col'].cumsum() # 累加和
df.apply(np.sqrt) # 应用函数 字符串操作(需转换为 str 类型): df['name'].str.upper() # 转大写
df['email'].str.contains('@gmail') # 匹配子串 对象类型处理: df['col'].astype('category') # 转换为分类类型
1.8 merge操作
表连接: pd.merge(left, right, on='key', how='inner') # 内连接 参数详解:
how: left, right, outer, inner suffixes: 解决列名冲突(如 _x, _y)
1.9 显示设置
调整显示选项: pd.set_option('display.max_rows', 100) # 最多显示100行
pd.set_option('display.float_format', '{:.2f}'.format) # 浮点数格式
1.10 数据透视表
快速汇总: pd.pivot_table(df, values='sales', index='region', columns='year', aggfunc=np.sum) 多层透视: pd.pivot_table(df, index=['region', 'year'], values='sales', aggfunc=[np.mean, np.sum])
1.11-1.12 时间操作
时间解析: df['date'] = pd.to_datetime(df['date']) # 转为时间类型
df['year'] = df['date'].dt.year # 提取年份 时间序列重采样: df.resample('M').mean() # 按月重采样
1.13-1.14 Pandas常用操作
去重与排序: df.drop_duplicates(subset='col') # 去重
df.sort_values(by='col', ascending=False) # 排序 缺失值处理: df.dropna() # 删除缺失值
df.fillna(method='ffill') # 前向填充
1.15 Groupby操作延伸
分组后过滤: df.groupby('group').filter(lambda x: x['value'].mean() > 10) # 筛选组 分组应用自定义函数: def normalize(x):
return (x - x.mean()) / x.std()
df.groupby('group').apply(normalize)
1.16 字符串操作
正则匹配: df['text'].str.extract(r'(\d+)') # 提取数字
df['text'].str.replace(r'\d+', 'NUM') # 替换数字
1.17 索引进阶
条件筛选: df.query('age > 30 & salary > 5000') # 查询语法
df.loc[df['age'] > 30, 'name'] # 标签定位
索引优化:
df = df.sort_index() # 索引排序提升查询速度
1.18 Pandas绘图操作
集成 Matplotlib: df.plot(x='date', y='price', kind='line') # 折线图
df['sales'].plot.hist(bins=20) # 直方图
1.19 大数据处理技巧
分块读取: chunk_iter = pd.read_csv('large.csv', chunksize=10000) # 分块读取
for chunk in chunk_iter:
process(chunk) 内存优化: df = df.astype({'col1': 'int32', 'col2': 'category'}) # 降低内存占用 并行处理: import swifter
df['new_col'] = df['col'].swifter.apply(lambda x: x*2) # 利用多核加速
总结
核心数据结构:Series 和 DataFrame 是 Pandas 的基石。 数据操作四要素:索引、分组、合并、清洗。 性能优化:类型转换、分块处理、并行计算。 实战场景:金融数据分析、日志处理、时间序列预测。
python 数据分析处理库-Pandas
推荐阅读 拼多多帮助力入口