954 字
5 分钟
数据分析|Series的创建、属性与索引

14.1 Series 结构
Series 是一种一维数组型对象,包含两个核心组成部分:
- 值序列(values):存储的实际数据
- 索引(index):每个数据对应的标签
结构图解
A1 12 23 34 4dtype: int64图示中 Series 分为三部分:
- Series Index:左侧数字 1、2、3、4,代表序列索引
- Series Name:顶部标识 A,代表序列名称
- Series Values:右侧数字 1、2、3、4,代表序列存储的数据
14.2 Series 的创建
14.2.1 通过列表创建
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5])print(s)输出:
0 11 22 33 44 5dtype: int64默认索引为从 0 开始的整数序列。
14.2.2 自定义索引
通过 index 参数可以为 Series 指定自定义的索引标签:
s = pd.Series([1, 2, 3, 4, 5], index=['A', 'B', 'C', 'D', 'E'])print(s)输出:
A 1B 2C 3D 4E 5dtype: int6414.2.3 指定名称
通过 name 参数可以为 Series 命名:
s = pd.Series([1, 2, 3, 4, 5], index=['A', 'B', 'C', 'D', 'E'], name='月份')print(s)输出:
A 1B 2C 3D 4E 5Name: 月份, dtype: int6414.2.4 通过字典创建
将字典的键作为索引、值作为数据创建 Series:
s = pd.Series({'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5})print(s)
# 通过已有 Series 和指定索引提取子集s1 = pd.Series(s, index=['a', 'c'])print(s1)输出:
a 1b 2c 3d 4e 5dtype: int64a 1c 3dtype: int64通过 pd.Series(s, index=[...]) 可以从已有 Series 中筛选出指定索引对应的元素,未匹配的索引会被忽略。
14.3 Series 的属性
Series 提供了丰富的属性来描述自身的特征:
| 属性 | 说明 |
|---|---|
index | Series 的索引对象 |
values | Series 的值 |
dtype 或 dtypes | Series 的元素类型 |
shape | Series 的形状 |
ndim | Series 的维度 |
size | Series 的元素个数 |
name | Series 的名称 |
loc[] | 显式索引,按标签索引或切片 |
iloc[] | 隐式索引,按位置索引或切片 |
at[] | 使用标签访问单个元素 |
iat[] | 使用位置访问单个元素 |
访问属性示例:
s = pd.Series({'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5})s.name = 'test'print(s.index)print(s.values)print(s.shape, s.ndim, s.size)print(s.dtype, s.name)输出:
Index(['a', 'b', 'c', 'd', 'e'], dtype='object')[1 2 3 4 5](5,) 1 5int64 test14.4 索引与访问
Pandas 提供了多种索引方式,分为显式索引(按标签)和隐式索引(按位置)。
print(s.loc['a']) # 显式索引,按标签访问print(s.iloc[0]) # 隐式索引,按位置访问print(s.at['a']) # 按标签访问单个元素(不支持切片)print(s.iat[0]) # 按位置访问单个元素(不支持切片)输出:
1111布尔索引:
print(s[s < 3]) # 筛选值小于3的元素输出:
a 1b 2Name: test, dtype: int64添加元素与预览:
s['f'] = 6 # 通过标签添加新元素print(s.head()) # 返回前5行print(s.tail()) # 返回后5行print(s.head(2)) # 返回前2行输出:
a 1b 2c 3d 4e 5Name: test, dtype: int64b 2c 3d 4e 5f 6Name: test, dtype: int64a 1b 2Name: test, dtype: int64要点说明:
loc[]按标签名访问(如s.loc['a']),支持切片(左右均包含)。iloc[]按位置序号访问(如s.iloc[0]),切片规则与 Python 一致(左闭右开)。at[]/iat[]仅用于访问单个元素,速度比loc/iloc更快。- 不推荐使用
s[0]直接访问,因为索引不清楚是显式还是隐式,容易产生歧义。
14.5 本节小结
本节完成了以下内容:
- 理解了 Series 的一维数组结构及其三要素:索引、名称、值。
- 掌握了 Series 的四种创建方式:列表(默认索引)、自定义索引、指定名称、字典创建。
- 熟悉了 Series 的常用属性:
index、values、dtype、shape、ndim、size、name。 - 掌握了显式索引(
loc、at)与隐式索引(iloc、iat)的区别与用法。 - 学会了布尔索引筛选、元素添加、
head()与tail()预览等实用操作。
下一节我们将学习 Series 的常用方法。
数据分析
连载中数据分析|Series的创建、属性与索引
https://luq-blog.xyz/posts/2026-07-03-data-notes-14-series-basics/分享文章
生成精美分享图或复制链接,与更多人分享本文。
继续阅读
换条路线
从其他文章中稳定抽取
最后更新于 ,距今已过 91 天
部分内容可能已过时
评论