📚 目录
- 什么是 Series?
- 创建 Series 的方法
- Series 的常用属性与方法
- Series 的索引操作
- 应用场景示例
- 参考资料
- 出站链接
1. 什么是 Series?
Series 是 Pandas 中最基本的数据结构之一,它是带有标签(索引)的一维数组。可以理解为带索引的 NumPy 数组,也可以类比为 Excel 中的一列。
2. 创建 Series 的方法
✅ 通过列表创建:
import pandas as pd
s = pd.Series([10, 20, 30, 40])
print(s)
输出:
0 10
1 20
2 30
3 40
dtype: int64
✅ 自定义索引:
s = pd.Series([100, 200, 300], index=['a', 'b', 'c'])
print(s)
输出:
a 100
b 200
c 300
dtype: int64
✅ 通过字典创建:
data = {'x': 1, 'y': 2, 'z': 3}
s = pd.Series(data)
print(s)
输出:
x 1
y 2
z 3
dtype: int64
3. Series 的常用属性与方法
属性/方法 | 说明 |
---|---|
s.index | 返回索引对象 |
s.values | 返回值数组(NumPy) |
s.dtype | 数据类型 |
s.shape | 数据结构形状 |
s.head() | 返回前 5 个元素 |
s.tail() | 返回后 5 个元素 |
4. Series 的索引操作
✅ 位置索引(类似数组):
s[0] # 访问第一个元素
✅ 标签索引(类似字典):
s['a'] # 访问索引为 'a' 的值
✅ 切片操作:
s[1:3] # 位置切片
s['b':'c'] # 标签切片,包含结束项
5. 应用场景示例
- 表示某城市每日温度数据
- 某产品每日销售额
- 某用户的评分记录
temps = pd.Series(
[22, 25, 23, 21],
index=['Mon', 'Tue', 'Wed', 'Thu']
)
📖 参考资料
- Pandas 官方 Series 文档:https://pandas.pydata.org/docs/reference/api/pandas.Series.html
- Real Python – Series 教程:https://realpython.com/pandas-python-explore-dataset/
发表回复