一、什么是 Series?
Series 是 Pandas 中的一个核心数据结构,类似于一个一维的数组,具有数据和索引。
Series 可以存储任何数据类型(整数、浮点数、字符串等),并通过标签(索引)来访问元素。它的数据结构非常有用,因为它可以处理各种数据类型,同时保持了高效的数据操作能力,比如可以通过标签来快速访问和操作数据。
Series 的特点:
| 特点 | 说明 |
|---|---|
| 一维数组 | Series 中的每个元素都有一个对应的索引值 |
| 索引 | 每个数据元素都可以通过标签(索引)来访问,默认从 0 开始的整数,也可自定义 |
| 数据类型 | 可以容纳不同数据类型的元素,包括整数、浮点数、字符串、Python 对象等 |
| 大小不变性 | Series 的大小在创建后是不变的,但可以通过某些操作(如 append 或 delete)来改变 |
| 操作 | 支持各种操作,如数学运算、统计分析、字符串处理等 |
| 缺失数据 | 可以包含缺失数据,Pandas 使用 NaN(Not a Number)来表示缺失或无值 |
| 自动对齐 | 当对多个 Series 进行运算时,Pandas 会自动根据索引对齐数据 |
二、Series 的组成
我们可以使用 Pandas 库来创建一个 Series 对象,并且可以为其指定索引(Index)、名称(Name)以及值(Values)。
python
import pandas as pd # 创建一个 Series 对象,指定名称为 'A',值分别为 1, 2, 3, 4 # 默认索引为 0, 1, 2, 3 series = pd.Series([1, 2, 3, 4], name='A') print(series) # 显式地设置索引 custom_index = [1, 2, 3, 4] series_with_index = pd.Series([1, 2, 3, 4], index=custom_index, name='A') print(series_with_index)
输出结果:
text
0 1 1 2 2 3 3 4 Name: A, dtype: int64 1 1 2 2 3 3 4 4 Name: A, dtype: int64
Series 的三个组成部分:
| 部分 | 说明 |
|---|---|
| 索引(Index) | 左侧的标签,默认 0 开始 |
| 值(Values) | 右侧的数据 |
| 名称(Name) | Series 的标识,可选 |
三、创建 Series
可以使用 pd.Series() 构造函数创建一个 Series 对象,传递一个数据数组(可以是列表、NumPy 数组等)和一个可选的索引数组。
python
pandas.Series(data=None, index=None, dtype=None, name=None, copy=False, fastpath=False)
参数说明:
| 参数 | 说明 |
|---|---|
data |
数据部分,可以是列表、数组、字典、标量值等。不提供则创建空 Series |
index |
索引部分,用于对数据进行标记。不提供则创建默认整数索引 |
dtype |
指定数据类型,如 np.int64、np.float64。不提供则自动推断 |
name |
Series 的名称,用于标识对象 |
copy |
是否复制数据,默认 False |
fastpath |
是否启用快速路径,默认 False |
1. 从列表创建
python
import pandas as pd a = [1, 2, 3] myvar = pd.Series(a) print(myvar)
如果没有指定索引,索引值就从 0 开始。我们可以根据索引值读取数据:
python
print(myvar[1]) # 输出 2
2. 指定索引
python
import pandas as pd a = ["Google", "Runoob", "Wiki"] myvar = pd.Series(a, index=["x", "y", "z"]) print(myvar) print(myvar["y"]) # 输出 Runoob
3. 从字典创建
python
import pandas as pd sites = {1: "Google", 2: "Runoob", 3: "Wiki"} myvar = pd.Series(sites) print(myvar)
从上图可知,字典的 key 变成了索引值。
如果我们只需要字典中的一部分数据,只需要指定需要数据的索引即可:
python
myvar = pd.Series(sites, index=[1, 2]) print(myvar)
4. 设置名称
python
sites = {1: "Google", 2: "Runoob", 3: "Wiki"} myvar = pd.Series(sites, index=[1, 2], name="RUNOOB-Series-TEST") print(myvar)
5. 从 NumPy 数组创建
python
import numpy as np s = pd.Series(np.array([1, 2, 3, 4]))
四种创建方式对比:
| 数据源 | 示例 | 索引来源 |
|---|---|---|
| 列表 | pd.Series([1, 2, 3]) |
默认 0, 1, 2 |
| 列表 + 索引 | pd.Series([1, 2, 3], index=['a','b','c']) |
自定义 |
| 字典 | pd.Series({'a': 1, 'b': 2}) |
字典的键 |
| NumPy 数组 | pd.Series(np.array([1, 2, 3])) |
默认 0, 1, 2 |
四、Series 方法速查
下面是 Series 中一些常用的方法:
| 方法名称 | 功能描述 |
|---|---|
index |
获取 Series 的索引 |
values |
获取 Series 的数据部分(返回 NumPy 数组) |
head(n) |
返回 Series 的前 n 行(默认为 5) |
tail(n) |
返回 Series 的后 n 行(默认为 5) |
dtype |
返回 Series 中数据的类型 |
shape |
返回 Series 的形状(行数) |
describe() |
返回 Series 的统计描述(如均值、标准差、最小值等) |
isnull() |
返回一个布尔 Series,表示每个元素是否为 NaN |
notnull() |
返回一个布尔 Series,表示每个元素是否不是 NaN |
unique() |
返回 Series 中的唯一值(去重) |
value_counts() |
返回 Series 中每个唯一值的出现次数 |
map(func) |
将指定函数应用于 Series 中的每个元素 |
apply(func) |
将指定函数应用于 Series 中的每个元素,常用于自定义操作 |
astype(dtype) |
将 Series 转换为指定的类型 |
sort_values() |
对 Series 中的元素进行排序(按值排序) |
sort_index() |
对 Series 的索引进行排序 |
dropna() |
删除 Series 中的缺失值(NaN) |
fillna(value) |
填充 Series 中的缺失值(NaN) |
replace(to_replace, value) |
替换 Series 中指定的值 |
cumsum() |
返回 Series 的累计求和 |
cumprod() |
返回 Series 的累计乘积 |
shift(periods) |
将 Series 中的元素按指定的步数进行位移 |
rank() |
返回 Series 中元素的排名 |
corr(other) |
计算 Series 与另一个 Series 的相关性(皮尔逊相关系数) |
cov(other) |
计算 Series 与另一个 Series 的协方差 |
to_list() |
将 Series 转换为 Python 列表 |
to_frame() |
将 Series 转换为 DataFrame |
iloc[] |
通过位置索引来选择数据 |
loc[] |
通过标签索引来选择数据 |
五、综合实例
python
import pandas as pd # 创建 Series data = [1, 2, 3, 4, 5, 6] index = ['a', 'b', 'c', 'd', 'e', 'f'] s = pd.Series(data, index=index) # 查看基本信息 print("索引:", s.index) print("数据:", s.values) print("数据类型:", s.dtype) print("前两行数据:", s.head(2)) # 使用 map 函数将每个元素加倍 s_doubled = s.map(lambda x: x * 2) print("元素加倍后:", s_doubled) # 计算累计和 cumsum_s = s.cumsum() print("累计求和:", cumsum_s) # 查找缺失值 print("缺失值判断:", s.isnull()) # 排序 sorted_s = s.sort_values() print("排序后的 Series:", sorted_s)
输出结果:
text
索引: Index(['a', 'b', 'c', 'd', 'e', 'f'], dtype='object') 数据: [1 2 3 4 5 6] 数据类型: int64 前两行数据: a 1 b 2 dtype: int64 元素加倍后: a 2 b 4 c 6 d 8 e 10 f 12 dtype: int64 累计求和: a 1 b 3 c 6 d 10 e 15 f 21 dtype: int64 缺失值判断: a False b False ...
六、基本操作详解
1. 访问与切片
python
# 指定索引创建 Series s = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd']) # 获取值 value = s[2] # 获取索引为 2 的值 print(s['a']) # 返回索引标签 'a' 对应的元素 # 获取多个值 subset = s[1:4] # 获取索引为 1 到 3 的值 # 索引和值的对应关系 for index, value in s.items(): print(f"Index: {index}, Value: {value}") # 使用切片语法访问一部分 print(s['a':'c']) # 返回索引标签 'a' 到 'c' 之间的元素 print(s[:3]) # 返回前三个元素
2. 修改与增删
python
# 为特定的索引标签赋值 s['a'] = 10 # 将索引标签 'a' 对应的元素修改为 10 # 通过赋值给新的索引标签来添加元素 s['e'] = 5 # 在 Series 中添加一个新的元素 # 使用 del 删除指定索引标签的元素 del s['a'] # 删除索引标签 'a' 对应的元素 # 使用 drop 方法删除一个或多个索引标签,并返回一个新的 Series s_dropped = s.drop(['b'])
注意:
del直接修改原 Series,drop()返回新的 Series,原数据不变。
3. 基本运算
python
# 算术运算 result = series * 2 # 所有元素乘以 2 # 过滤 filtered_series = series[series > 2] # 选择大于 2 的元素 # 数学函数 import numpy as np result = np.sqrt(series) # 对每个元素取平方根
4. 统计计算
python
print(s.sum()) # 总和 print(s.mean()) # 平均值 print(s.max()) # 最大值 print(s.min()) # 最小值 print(s.std()) # 标准差
5. 属性和方法
python
index = s.index # 获取索引 values = s.values # 获取值数组 stats = s.describe() # 描述统计信息 max_index = s.idxmax() # 最大值的索引 min_index = s.idxmin() # 最小值的索引 print(s.dtype) # 数据类型 print(s.shape) # 形状 print(s.size) # 元素个数 print(s.head()) # 前几个元素,默认前 5 个 print(s.tail()) # 后几个元素,默认后 5 个
6. 布尔表达式
python
print(s > 2) # 返回一个布尔 Series
7. 类型转换
python
s = s.astype('float64') # 转换为 float64 类型
七、Series 注意事项
| 注意事项 | 说明 |
|---|---|
| 数据有序 | Series 中的数据是有序的 |
| 带索引的数组 | 可以将 Series 视为带有索引的一维数组 |
| 索引可重复 | 索引可以是唯一的,但不是必须的 |
| 数据来源广 | 数据可以是标量、列表、NumPy 数组等 |
八、Series 操作流程图
九、常见问题排查
| 问题现象 | 可能原因 | 解决方案 |
|---|---|---|
KeyError |
索引不存在 | 检查索引标签拼写 |
IndexError |
位置索引越界 | 检查索引范围 |
| 数据类型不符预期 | 自动推断错误 | 显式指定 dtype |
| 运算结果含 NaN | 索引未对齐 | 检查两个 Series 的索引 |
del 后原数据变化 |
del 是原地删除 |
如需保留原数据用 drop() |
| 切片结果与预期不符 | 标签切片含端点 | 标签切片 s['a':'c'] 包含 'c' |
重要区别: 位置切片
s[1:4]不包含末端,标签切片s['a':'c']包含末端。
十、小结
本篇你全面掌握了 Pandas Series 的用法:
-
定位:带标签的一维数组,可存储任意数据类型。
-
创建:从列表、字典、NumPy 数组创建,支持自定义索引与名称。
-
访问 :位置索引、标签索引、切片、
loc、iloc。 -
方法 :
head、tail、describe、map、apply、sort_values等。 -
运算:算术运算、数学函数、布尔过滤、统计计算。
-
增删改 :赋值、
del、drop。 -
类型转换 :
astype、to_list、to_frame。
Series 是一维数据的载体,也是理解 DataFrame 的基础。下一篇我们将深入学习 DataFrame 数据结构,掌握二维表格数据的创建与操作。