1.3 Pandas 数据结构:Series


文档摘要

1.3 Pandas 数据结构:Series 1.3 Pandas 数据结构:Series Pandas 库的核心是两种主要的数据结构:Series(一维)和 DataFrame(二维)。本节将深入探讨 Series 数据结构,包括其创建、属性、操作和应用。 1.3.1 Series 的定义 Series 是一个带有标签(索引)的一维数组,可以存储任何数据类型(整数、浮点数、字符串、Python 对象等)。可以将 Series 视为带有行标签的 DataFrame 的单列。 关键特性: 数据(Data): Series 存储的实际数据。 索引(Index): 与数据关联的标签,用于访问数据。索引可以是数字、字符串或任何其他可哈希的 Python 对象。

1.3 Pandas 数据结构:Series

1.3 Pandas 数据结构:Series

Pandas 库的核心是两种主要的数据结构:Series(一维)和 DataFrame(二维)。本节将深入探讨 Series 数据结构,包括其创建、属性、操作和应用。

1.3.1 Series 的定义

Series 是一个带有标签(索引)的一维数组,可以存储任何数据类型(整数、浮点数、字符串、Python 对象等)。可以将 Series 视为带有行标签的 DataFrame 的单列。

关键特性:

  • 数据(Data): Series 存储的实际数据。

  • 索引(Index): 与数据关联的标签,用于访问数据。索引可以是数字、字符串或任何其他可哈希的 Python 对象。

  • 数据类型(dtype): Series 中数据的数据类型。

1.3.2 创建 Series

可以使用多种方式创建 Series:

1. 从列表或 NumPy 数组创建:

import pandas as pd import numpy as np # 从列表创建 data = [10, 20, 30, 40, 50] s1 = pd.Series(data) print("从列表创建的 Series:\n", s1) # 从 NumPy 数组创建 data_np = np.array([1, 3, 5, 7, 9]) s2 = pd.Series(data_np) print("\n从 NumPy 数组创建的 Series:\n", s2)

输出:

从列表创建的 Series: 0 10 1 20 2 30 3 40 4 50 dtype: int64 从 NumPy 数组创建的 Series: 0 1 1 3 2 5 3 7 4 9 dtype: int64

2. 从字典创建:

字典的键将成为 Series 的索引,值将成为 Series 的数据。

data_dict = {'a': 100, 'b': 200, 'c': 300} s3 = pd.Series(data_dict) print("\n从字典创建的 Series:\n", s3)

输出:

从字典创建的 Series: a 100 b 200 c 300 dtype: int64

3. 指定索引:

可以在创建 Series 时显式指定索引。

data = [1, 2, 3, 4, 5] index = ['A', 'B', 'C', 'D', 'E'] s4 = pd.Series(data, index=index) print("\n指定索引的 Series:\n", s4)

输出:

指定索引的 Series: A 1 B 2 C 3 D 4 E 5 dtype: int64

4. 使用标量值创建:

创建一个 Series,其中所有值都相同。

s5 = pd.Series(5, index=['p', 'q', 'r', 's']) print("\n使用标量值创建的 Series:\n", s5)

输出:

使用标量值创建的 Series: p 5 q 5 r 5 s 5 dtype: int64

1.3.3 Series 的属性

Series 对象具有许多有用的属性,可以帮助我们了解其结构和内容:

  • index: 返回 Series 的索引。

  • values: 返回 Series 的数据(NumPy 数组)。

  • dtype: 返回 Series 的数据类型。

  • shape: 返回 Series 的形状(大小)。

  • size: 返回 Series 中元素的数量。

  • empty: 如果 Series 为空,则返回 True,否则返回 False。

  • name: 返回 Series 的名称(可选)。

print("\nSeries 的属性:") print("Index:", s4.index) print("Values:", s4.values) print("Data Type:", s4.dtype) print("Shape:", s4.shape) print("Size:", s4.size) print("Empty:", s4.empty) s4.name = "Example Series" print("Name:", s4.name)

输出:

Series 的属性: Index: Index(['A', 'B', 'C', 'D', 'E'], dtype='object') Values: [1 2 3 4 5] Data Type: int64 Shape: (5,) Size: 5 Empty: False Name: Example Series

1.3.4 访问 Series 中的数据

可以使用索引标签或位置(整数索引)访问 Series 中的数据。

1. 使用标签索引:

print("\n使用标签索引访问数据:") print("s4['A']:", s4['A']) print("s4[['A', 'C', 'E']]:\n", s4[['A', 'C', 'E']]) # 访问多个元素

输出:

使用标签索引访问数据: s4['A']: 1 s4[['A', 'C', 'E']]: A 1 C 3 E 5 Name: Example Series, dtype: int64

2. 使用位置索引(整数索引):

print("\n使用位置索引访问数据:") print("s4[0]:", s4[0]) print("s4[[0, 2, 4]]:\n", s4[[0, 2, 4]]) # 访问多个元素 print("s4[1:4]:\n", s4[1:4]) #切片

输出:

使用位置索引访问数据: s4[0]: 1 s4[[0, 2, 4]]: A 1 C 3 E 5 Name: Example Series, dtype: int64 s4[1:4]: B 2 C 3 D 4 Name: Example Series, dtype: int64

注意: 当索引是整数时,需要小心区分标签索引和位置索引。为了避免混淆,可以使用 .loc (标签索引) 和 .iloc (位置索引) 属性进行显式访问。

print("\n使用 .loc 和 .iloc 访问数据:") print("s4.loc['A']:", s4.loc['A']) print("s4.iloc[0]:", s4.iloc[0])

输出:

使用 .loc 和 .iloc 访问数据: s4.loc['A']: 1 s4.iloc[0]: 1

1.3.5 Series 的操作

Pandas Series 支持各种操作,包括算术运算、比较运算、布尔索引等。

1. 算术运算:

s6 = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd']) s7 = pd.Series([5, 6, 7, 8], index=['a', 'b', 'c', 'd']) print("\n算术运算:") print("s6 + s7:\n", s6 + s7) print("s6 * 2:\n", s6 * 2)

输出:

算术运算: s6 + s7: a 6 b 8 c 10 d 12 dtype: int64 s6 * 2: a 2 b 4 c 6 d 8 dtype: int64

如果 Series 的索引不完全匹配,Pandas 会自动对齐索引,并将缺失值填充为 NaN

s8 = pd.Series([1, 2, 3], index=['a', 'b', 'c']) s9 = pd.Series([4, 5, 6], index=['b', 'c', 'd']) print("\n索引不对齐的算术运算:") print("s8 + s9:\n", s8 + s9)

输出:

索引不对齐的算术运算: s8 + s9: a NaN b 6.0 c 8.0 d NaN dtype: float64

2. 比较运算:

print("\n比较运算:") print("s6 > 2:\n", s6 > 2)

输出:

比较运算: s6 > 2: a False b False c True d True dtype: bool

3. 布尔索引:

使用布尔 Series 过滤数据。

print("\n布尔索引:") print("s6[s6 > 2]:\n", s6[s6 > 2])

输出:

布尔索引: s6[s6 > 2]: c 3 d 4 dtype: int64

4. 成员资格判断:

print("\n成员资格判断:") print("s6.isin([2, 4]):\n", s6.isin([2, 4]))

输出:

成员资格判断: s6.isin([2, 4]): a False b True c False d True dtype: bool

1.3.6 处理缺失数据

Series 可以包含缺失值,通常表示为 NaN(Not a Number)。 Pandas 提供了处理缺失值的函数:

  • isnull(): 检测缺失值,返回布尔 Series。

  • notnull(): 检测非缺失值,返回布尔 Series。

  • dropna(): 删除包含缺失值的行。

  • fillna(): 用指定值填充缺失值。

s10 = pd.Series([1, 2, np.nan, 4, np.nan]) print("\n包含缺失值的 Series:\n", s10) print("\nisnull():\n", s10.isnull()) print("\nnotnull():\n", s10.notnull()) print("\ndropna():\n", s10.dropna()) print("\nfillna(0):\n", s10.fillna(0)) # 用0填充 print("\nfillna(s10.mean()):\n", s10.fillna(s10.mean())) # 用均值填充

输出:

包含缺失值的 Series: 0 1.0 1 2.0 2 NaN 3 4.0 4 NaN dtype: float64 isnull(): 0 False 1 False 2 True 3 False 4 True dtype: bool notnull(): 0 True 1 True 2 False 3 True 4 False dtype: bool dropna(): 0 1.0 1 2.0 3 4.0 dtype: float64 fillna(0): 0 1.0 1 2.0 2 0.0 3 4.0 4 0.0 dtype: float64 fillna(s10.mean()): 0 1.0 1 2.0 2 2.333333 3 4.0 4 2.333333 dtype: float64

1.3.7 Series 的应用

Series 在数据分析中扮演着重要的角色。 它们可以用于:

  • 表示时间序列数据。

  • 存储分类数据。

  • 作为 DataFrame 的列。

  • 执行统计分析。

1.3.8 Mermaid 图表辅助理解

以下 Mermaid 图表可以帮助理解 Series 的结构:

图表解释:

  • Series 是最顶层的概念,它包含 IndexDatadtype 三个关键组件。

  • Index 存储 Series 的标签,用于访问数据。

  • Data 存储 Series 的实际数据值。

  • dtype 表示 Series 中数据的数据类型。

这个图表直观地展示了 Series 的内部结构,有助于更好地理解其概念。

1.3.9 总结

Pandas Series 是一种强大而灵活的数据结构,用于表示一维带标签的数据。 掌握 Series 的创建、属性、操作和应用对于使用 Pandas 进行数据分析至关重要。 通过本节的学习,您应该能够熟练地使用 Series 来处理各种数据分析任务。


作者与出处
原作者: 灏天文库
来源:灏天文库
整理: 灏天文库整理
由灏天文库平台收录,内容或由平台用户上传,仅供学习交流
发布者: 作者: 灏天文库 转发
评论区 (0)
U