954 字
5 分钟
页面浏览--访问次数--
数据分析|Series的创建、属性与索引

14.1 Series 结构#

Series 是一种一维数组型对象,包含两个核心组成部分:

  • 值序列(values):存储的实际数据
  • 索引(index):每个数据对应的标签

结构图解#

A
1 1
2 2
3 3
4 4
dtype: int64

图示中 Series 分为三部分:

  1. Series Index:左侧数字 1、2、3、4,代表序列索引
  2. Series Name:顶部标识 A,代表序列名称
  3. 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 1
1 2
2 3
3 4
4 5
dtype: int64

默认索引为从 0 开始的整数序列。

14.2.2 自定义索引#

通过 index 参数可以为 Series 指定自定义的索引标签:

s = pd.Series([1, 2, 3, 4, 5], index=['A', 'B', 'C', 'D', 'E'])
print(s)

输出:

A 1
B 2
C 3
D 4
E 5
dtype: int64

14.2.3 指定名称#

通过 name 参数可以为 Series 命名:

s = pd.Series([1, 2, 3, 4, 5], index=['A', 'B', 'C', 'D', 'E'], name='月份')
print(s)

输出:

A 1
B 2
C 3
D 4
E 5
Name: 月份, dtype: int64

14.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 1
b 2
c 3
d 4
e 5
dtype: int64
a 1
c 3
dtype: int64

通过 pd.Series(s, index=[...]) 可以从已有 Series 中筛选出指定索引对应的元素,未匹配的索引会被忽略。


14.3 Series 的属性#

Series 提供了丰富的属性来描述自身的特征:

属性说明
indexSeries 的索引对象
valuesSeries 的值
dtype 或 dtypesSeries 的元素类型
shapeSeries 的形状
ndimSeries 的维度
sizeSeries 的元素个数
nameSeries 的名称
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 5
int64 test

14.4 索引与访问#

Pandas 提供了多种索引方式,分为显式索引(按标签)和隐式索引(按位置)。

print(s.loc['a']) # 显式索引,按标签访问
print(s.iloc[0]) # 隐式索引,按位置访问
print(s.at['a']) # 按标签访问单个元素(不支持切片)
print(s.iat[0]) # 按位置访问单个元素(不支持切片)

输出:

1
1
1
1

布尔索引:

print(s[s < 3]) # 筛选值小于3的元素

输出:

a 1
b 2
Name: test, dtype: int64

添加元素与预览:

s['f'] = 6 # 通过标签添加新元素
print(s.head()) # 返回前5行
print(s.tail()) # 返回后5行
print(s.head(2)) # 返回前2行

输出:

a 1
b 2
c 3
d 4
e 5
Name: test, dtype: int64
b 2
c 3
d 4
e 5
f 6
Name: test, dtype: int64
a 1
b 2
Name: 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 的常用方法。


数据分析

连载中

第 14 篇,共 21 篇本文属于系列

数据分析|Series的创建、属性与索引
https://luq-blog.xyz/posts/2026-07-03-data-notes-14-series-basics/
作者
Luquiescene
发布于
2026-07-03
许可协议
CC BY-NC-SA 4.0

分享文章

生成精美分享图或复制链接,与更多人分享本文。

继续阅读

沿着主题读

基于共同的标签与分类

换条路线

从其他文章中稳定抽取

评论

正在加载评论...

最后更新于 ,距今已过 91 天

部分内容可能已过时