
16.1 案例概述
本节通过五个实际案例,综合运用 Series 的创建、筛选、统计、排序等方法,巩固前几节所学知识。
使用的库:
import numpy as npimport pandas as pd16.2 学生成绩统计
生成 10 名学生的随机成绩,进行基本统计分析。
np.random.seed(42)scores = pd.Series(np.random.randint(50, 101, 10), index=['学生' + str(i) for i in range(1, 11)])print(scores)输出:
学生1 88学生2 78学生3 64学生4 92学生5 57学生6 70学生7 88学生8 68学生9 72学生10 60dtype: int32print('平均分:', scores.mean())print('最高分:', scores.max())print('最低分:', scores.min())print('高于平均分的人数:', scores[scores > scores.mean()].count())输出:
平均分: 73.7最高分: 92最低分: 57高于平均分的人数: 4涉及方法: mean()、max()、min()、布尔索引筛选、count()。
16.3 温度数据分析
分析一周温度数据,找出最高温所在日和温度变化最大的两天。
temperatures = pd.Series([28, 31, 29, 32, 30, 27, 33], index=['周一', '周二', '周三', '周四', '周五', '周六', '周日'])# 温度超过30的天数print('超30℃天数:', temperatures[temperatures > 30].count())print('平均温度:', temperatures.mean())
# 按温度降序排列print(temperatures.sort_values(ascending=False))输出:
超30℃天数: 3平均温度: 30.0周日 33周四 32周二 31周五 30周三 29周一 28周六 27dtype: int64# 计算温度变化最大的两天# 原始温度: 28 31 29 32 30 27 33# 相邻差: nan 3 -2 3 -2 -3 6t3 = temperatures.diff().abs()print('温度变化最大的2天:', t3.sort_values(ascending=False).index[:2].tolist())输出:
温度变化最大的2天: ['周日', '周二']分析过程:
diff():计算相邻两天的温差。abs():取绝对值,获取变化幅度(不分正负)。sort_values(ascending=False):按变化幅度降序排列。index[:2].tolist():取前两名的索引(周几)并转为列表。
16.4 股票价格分析
模拟 10 天的股票收盘价,计算每日收益率和波动率。
prices = pd.Series([102.3, 103.5, 105.1, 104.8, 106.2, 107.0, 106.5, 108.1, 109.3, 110.2], index=pd.date_range('2023-01-01', periods=10))print(prices)输出:
2023-01-01 102.32023-01-02 103.52023-01-03 105.12023-01-04 104.82023-01-05 106.22023-01-06 107.02023-01-07 106.52023-01-08 108.12023-01-09 109.32023-01-10 110.2Freq: D, dtype: float64pd.date_range() 可以快速生成连续的日期索引,periods 指定生成天数。
# 每日收益率 = 当日收盘价 / 前日收盘价 - 1a = prices.pct_change()print(a)输出:
2023-01-01 NaN2023-01-02 0.0117302023-01-03 0.0154592023-01-04 -0.0028542023-01-05 0.0133592023-01-06 0.0075332023-01-07 -0.0046732023-01-08 0.0150232023-01-09 0.0111012023-01-10 0.008234Freq: D, dtype: float64第一天为 NaN,因为没有前一天的数据可供计算。
print('收益率最高的日期:', a.idxmax())print('收益率最低的日期:', a.idxmin())print('波动率(标准差):', a.std())输出:
收益率最高的日期: 2023-01-03 00:00:00收益率最低的日期: 2023-01-07 00:00:00波动率(标准差): 0.007373623845361105涉及方法: pd.date_range()、pct_change()、idxmax()、idxmin()、std()。
16.5 销售数据分析
分析 2022 年月度销售数据,实现季度汇总和连续增长检测。
sales = pd.Series([120, 135, 145, 160, 155, 170, 180, 175, 190, 200, 210, 220], index=pd.date_range('2022-01-01', periods=12, freq='MS'))print(sales)输出:
2022-01-01 1202022-02-01 1352022-03-01 1452022-04-01 1602022-05-01 1552022-06-01 1702022-07-01 1802022-08-01 1752022-09-01 1902022-10-01 2002022-11-01 2102022-12-01 220Freq: MS, dtype: int64freq='MS' 表示月初(Month Start),生成每月第一天。
季度平均销量:
print(sales.resample('QS').mean())输出:
2022-01-01 133.3333332022-04-01 161.6666672022-07-01 181.6666672022-10-01 210.000000Freq: QS-JAN, dtype: float64resample('QS') 按季度(Quarter Start)对时间序列做重采样,配合 mean() 计算每季度平均值。
月环比增长率:
print(sales.pct_change())输出:
2022-01-01 NaN2022-02-01 0.1250002022-03-01 0.0740742022-04-01 0.1034482022-05-01 -0.0312502022-06-01 0.0967742022-07-01 0.0588242022-08-01 -0.0277782022-09-01 0.0857142022-10-01 0.0526322022-11-01 0.0500002022-12-01 0.047619Freq: MS, dtype: float64连续增长超过 2 个月的月份(滑动窗口算法):
a = sales.pct_change()b = a > 0print(list(b[b.rolling(3).sum() == 3].keys()))输出:
[Timestamp('2022-04-01 00:00:00'), Timestamp('2022-11-01 00:00:00'), Timestamp('2022-12-01 00:00:00')]分析过程:
pct_change():计算逐月环比增长率。> 0:生成布尔 Series,标记增长(True)或下降(False)。rolling(3).sum():滑动窗口大小为 3,计算连续 3 个月中增长的月份数。== 3:筛选出连续 3 个月都增长的月份。
涉及方法: resample()、pct_change()、idxmax()、rolling()、keys()。
16.6 每小时销售数据分析
生成一天 24 小时的随机销售数据,按天聚合计算总销售额。
np.random.seed(42)hourly_sales = pd.Series(np.random.randint(1, 100, 24), index=pd.date_range('2025-01-01', periods=24, freq='h'))print(hourly_sales)输出:
2025-01-01 00:00:00 522025-01-01 01:00:00 932025-01-01 02:00:00 152025-01-01 03:00:00 722025-01-01 04:00:00 612025-01-01 05:00:00 212025-01-01 06:00:00 832025-01-01 07:00:00 872025-01-01 08:00:00 752025-01-01 09:00:00 752025-01-01 10:00:00 882025-01-01 11:00:00 242025-01-01 12:00:00 32025-01-01 13:00:00 222025-01-01 14:00:00 532025-01-01 15:00:00 22025-01-01 16:00:00 882025-01-01 17:00:00 302025-01-01 18:00:00 382025-01-01 19:00:00 22025-01-01 20:00:00 642025-01-01 21:00:00 602025-01-01 22:00:00 212025-01-01 23:00:00 33Freq: h, dtype: int32freq='h' 表示按小时生成时间序列。
按天汇总总销售额:
print(hourly_sales.resample('D').sum())输出:
2025-01-01 1162Freq: D, dtype: int32resample('D') 将 24 条小时数据聚合为 1 条日数据,配合 sum() 计算当天总销售额。
16.7 本节小结
本节通过五个案例综合运用了 Series 的核心方法:
| 案例 | 涉及方法 |
|---|---|
| 学生成绩统计 | mean()、max()、min()、布尔索引、count() |
| 温度数据分析 | sort_values()、diff()、abs()、tolist() |
| 股票价格分析 | pd.date_range()、pct_change()、idxmax()、idxmin()、std() |
| 销售数据分析 | resample()、pct_change()、rolling()、keys() |
| 每小时销售分析 | pd.date_range(freq='h')、resample('D').sum() |
下一节我们将学习 DataFrame 的介绍和创建。
数据分析
连载中分享文章
生成精美分享图或复制链接,与更多人分享本文。
继续阅读
换条路线
从其他文章中稳定抽取
最后更新于 ,距今已过 93 天
部分内容可能已过时
评论