Pandas 数据结构 - Series

Pandas 数据结构 - Series

一、Series 简介

Series 是一种一维数据结构。你可以把它想象成一个带标签的数组有序的字典。它由两部分组成:

  1. 数据值 (values): 可以是整数、浮点数、字符串、Python 对象等。这些数据存储在类似于 NumPy 数组的结构中。
  2. 索引 (index) : 与每个数据值相关联的标签。索引允许你像字典一样通过标签访问数据。默认情况下,如果没有显式提供索引,Pandas 会创建一个从 0 开始的整数索引 (0, 1, 2, ..., n-1)

核心特点

  • 一维结构
  • 能够存储任何数据类型
  • 具有索引,支持高效的基于标签的查找
  • 自动对齐索引进行运算
  • 类似于一个固定长度、有序的字典

二、创建 Series

有多种方法可以创建 Series。

1、从列表创建

python 复制代码
import pandas as pd

# 创建一个简单的 Series (使用默认索引)
s1 = pd.Series([10, 20, 30, 40])
print(s1)

# 输出:
# 0    10
# 1    20
# 2    30
# 3    40
# dtype: int64

# 创建时指定索引
s2 = pd.Series([88, 92, 79, 95], index=['张三', '李四', '王五', '赵六'])
print(s2)

# 输出:
# 张三    88
# 李四    92
# 王五    79
# 赵六    95
# dtype: int64

2、从字典创建

字典的会自动成为 Series 的索引,字典的成为 Series 的数据

python 复制代码
student_scores = {'张三': 88, '李四': 92, '王五': 79, '赵六': 95}
s3 = pd.Series(student_scores)
print(s3)

# 输出:
# 张三    88
# 李四    92
# 王五    79
# 赵六    95
# dtype: int64

3、从标量值创建

如果提供单个标量值,需要同时指定索引,该标量值会被复制以匹配索引的长度。

python 复制代码
s4 = pd.Series(7, index=['a', 'b', 'c', 'd'])
print(s4)

# 输出:
# a    7
# b    7
# c    7
# d    7
# dtype: int64

4、从 NumPy 数组创建

python 复制代码
import numpy as np

data = np.array([10, 20, 30, 40])
s5 = pd.Series(data, index=['A', 'B', 'C', 'D'])
print(s5)

# 输出:
# A    10
# B    20
# C    30
# D    40
# dtype: int32

三、访问 Series 中的数据

1、使用索引标签访问 (类似字典)

python 复制代码
s = pd.Series([88, 92, 79, 95], index=['张三', '李四', '王五', '赵六'])

# 获取单个值
print(s['李四'])  # 输出: 92

# 获取多个值 (传入标签列表)
print(s[['张三', '王五']])

# 输出:
# 张三    88
# 王五    79
# dtype: int64

2、使用位置索引访问 (类似数组)

python 复制代码
s = pd.Series([88, 92, 79, 95], index=['张三', '李四', '王五', '赵六'])

# 获取第一个元素
print(s[0])  # 输出: 88

# 切片 (注意:基于位置,不包括结束位置)
print(s[1:3])

# 输出:
# 李四    92
# 王五    79
# dtype: int64

3、使用 .loc[] (基于标签的索引)

.loc[] 主要用于显式的索引标签。

python 复制代码
s = pd.Series([88, 92, 79, 95], index=['张三', '李四', '王五', '赵六'])

# 获取单个标签
print(s.loc['张三'])  # 输出: 88

# 获取多个标签
print(s.loc[['李四', '赵六']])

# 输出:
# 李四    92
# 赵六    95
# dtype: int64

# 切片 (基于标签,包括结束标签)
print(s.loc['张三':'王五'])  # 包含 '张三', '李四', '王五'

# 输出:
# 张三    88
# 李四    92
# 王五    79
# dtype: int64

4、使用 .iloc[] (基于位置的索引)

.iloc[] 用于基于整数位置的索引,与 Python/NumPy 的索引规则一致。

python 复制代码
s = pd.Series([88, 92, 79, 95], index=['张三', '李四', '王五', '赵六'])

# 获取第一个元素
print(s.iloc[0])  # 输出: 88

# 获取最后一个元素
print(s.iloc[-1])  # 输出: 95

# 获取多个位置
print(s.iloc[[0, 2]])  # 输出: 张三(88), 王五(79)

# 切片 (基于位置,不包括结束位置)
print(s.iloc[1:3])  # 输出: 李四(92), 王五(79)

四、Series 的基本属性和方法

1、查看索引和数据

python 复制代码
s = pd.Series([88, 92, 79, 95], index=['张三', '李四', '王五', '赵六'])

print(s.index)  # 输出: Index(['张三', '李四', '王五', '赵六'], dtype='object')
print(s.values)  # 输出: [88 92 79 95] (这是一个 NumPy 数组)

2、查看数据类型

python 复制代码
print(s.dtype)  # 输出: int64 (取决于数据内容)

3、查看 Series 的名称

可以为 Series 设置一个名称,这在与其他数据结构结合时很有用。

python 复制代码
s.name = '数学成绩'
s.index.name = '学生姓名'
print(s)

# 输出:
# 学生姓名
# 张三    88
# 李四    92
# 王五    79
# 赵六    95
# Name: 数学成绩, dtype: int64

4、常用统计方法

Series 提供了许多方便的统计方法。

python 复制代码
s = pd.Series([88, 92, 79, 95])

print(s.mean())  # 平均值
print(s.sum())  # 总和
print(s.min())  # 最小值
print(s.max())  # 最大值
print(s.std())  # 标准差
print(s.median())  # 中位数
print(s.describe())  # 主要统计信息汇总

5、向量化操作

Series 支持向量化的算术运算(基于元素),并自动对齐索引。

python 复制代码
s1 = pd.Series([10, 20, 30, 40])
s2 = pd.Series([1, 2, 3, 4], index=[0, 1, 2, 3])  # 索引匹配

print(s1 + s2)

# 输出:
# 0    11
# 1    22
# 2    33
# 3    44
# dtype: int64

s3 = pd.Series([1, 2, 3], index=['a', 'b', 'c'])
s4 = pd.Series([10, 20, 30], index=['b', 'c', 'd'])  # 索引部分匹配

print(s3 + s4)  # 索引对齐,不匹配的位置结果为 NaN (缺失值)

# 输出:
# a     NaN
# b    12.0
# c    23.0
# d     NaN
# dtype: float64

6、布尔索引

可以使用布尔表达式过滤数据。

python 复制代码
s = pd.Series([88, 92, 79, 95], index=['张三', '李四', '王五', '赵六'])

# 找出成绩大于 90 的学生
high_scores = s[s > 90]
print(high_scores)

# 输出:
# 李四    92
# 赵六    95
# dtype: int64

7、处理缺失值

Pandas 用 NaN (Not a Number,非数,表示未定义或不可表示的值。)表示缺失值。

python 复制代码
s = pd.Series([88, None, 79, 95])  # None 会被转换为 NaN
print(s.isna())  # 检查哪些位置是缺失值
print(s.fillna(0))  # 用 0 填充缺失值
print(s.dropna())  # 删除缺失值所在的行

五、Series常用方法总结

创建与初始化方法

Series(data, index, dtype, name, copy):核心构造函数,支持从列表、字典、ndarray等创建Series。
from_array():从数组创建(已弃用,推荐直接使用构造函数)。
from_dict():从字典创建,键自动成为索引。

数据访问与选择

[]loc[]:基于标签的索引访问。
iloc[]:基于整数位置的索引访问。
at[]:快速访问单个标签的值。
iat[]:快速访问单个整数位置的值。
head(n)/tail(n):返回前/后n行数据。
get(key, default=None):安全获取值,类似字典操作。

数据操作与修改

append():连接多个Series(已弃用,推荐pd.concat)。
drop():删除指定标签的行。
drop_duplicates():去除重复值。
fillna():填充缺失值。
replace():替换指定值。
update():用另一个Series的值更新当前Series。

统计与计算

sum()/mean()/median():求和、均值、中位数。
min()/max():最小/最大值。
std()/var():标准差/方差。
describe():生成描述性统计摘要。
value_counts():统计唯一值频率。
unique():返回唯一值数组。
nunique():返回唯一值数量。

排序与排名

sort_index():按索引排序。
sort_values():按值排序。
rank():计算排名(支持多种方法如平均、最小、最大排名)。

缺失值处理

isna()/isnull():检测缺失值。
notna()/notnull():检测非缺失值。
dropna():删除缺失值所在行。

类型转换与检查

astype(dtype):强制转换数据类型。
infer_objects():尝试推断更合适的数据类型。
convert_dtypes():转换为最佳支持的数据类型。

索引操作

reset_index():重置索引为默认整数索引。
set_index():将某列设为索引(适用于DataFrame中的Series)。
reindex():按新索引重新排列,可填充缺失值。

时间序列处理

to_timestamp()/to_period():转换为时间戳或周期。
dt访问器:访问日期时间属性(如dt.year)。

字符串处理

str访问器:支持向量化字符串操作(如str.upper())。

绘图与可视化

plot():调用Matplotlib绘制基本图形(需安装matplotlib)。

其他实用方法

copy():创建深层副本。
equals():检查两个Series是否完全相同。
to_dict():转换为Python字典。
to_list():转换为Python列表。
to_frame():将Series转换为DataFrame。

二进制与IO操作

to_pickle():序列化到文件。
to_csv():导出为CSV文件。
to_json():导出为JSON格式。

注意:部分方法(如append())已标记为弃用,建议使用Pandas更通用的函数(如pd.concat)替代。

相关推荐
蒙奇D索大2 小时前
【数据结构】考研408 | 平方探测法精讲:跳跃探查的艺术与聚集迷思
数据结构·笔记·考研·改行学it
无限进步_3 小时前
【C语言】队列(Queue)数据结构的实现与分析
c语言·开发语言·数据结构·c++·算法·链表·visual studio
重生之我是Java开发战士3 小时前
【算法日记】排序算法:原理、实现、性能与应用
数据结构·算法·排序算法
zz0723204 小时前
数据结构 —— 字典树
数据结构
液态不合群4 小时前
查找算法详解
java·数据结构·算法
LYFlied5 小时前
【每日算法】LeetCode 105. 从前序与中序遍历序列构造二叉树
数据结构·算法·leetcode·面试·职场和发展
重生之我是Java开发战士5 小时前
【数据结构】Java对象的比较
java·jvm·数据结构
历程里程碑5 小时前
C++ 16:C++11新特化
c语言·开发语言·数据结构·c++·经验分享
_dindong5 小时前
算法杂谈:回溯路线
数据结构·算法·动态规划·bfs·宽度优先