Pandas库--Series

1.Series

Series是一种类似于一维数组的对象,它由一维数组(各种numpy数据类型)以及一组与之相关的数据标签(即索引)组成.

可理解为带标签的一维数组,可存储整数、浮点数、字符串、Python 对象等类型的数据。

1
2
3
4
5
6
7
8
9
10
11
import pandas as pd
import numpy as np
 
s = pd.Series(['a','b','c','d','e'])
print(s)
0    a
1    b
2    c
3    d
4    e
dtype: object

 

Seris中可以使用index设置索引列表。与字典不同的是,Seris允许索引重复

1
2
3
4
5
6
7
8
9
#与字典不同的是:Series允许索引重复
s = pd.Series(['a','b','c','d','e'],index=[100,200,100,400,500])
print(s)
100    a
200    b
100    c
400    d
500    e
dtype: object

Series 可以用字典实例化

1
2
3
4
5
6
d = {'b': 1, 'a': 0, 'c': 2}
pd.Series(d)
b    1
a    0
c    2
dtype: int64

可以通过Series的values和index属性获取其数组表示形式和索引对象

1
2
3
4
5
6
7
8
9
10
11
print(s)
print(s.values)
print(s.index)
100    a
200    b
100    c
400    d
500    e
dtype: object
['a' 'b' 'c' 'd' 'e']
Int64Index([100, 200, 100, 400, 500], dtype='int64')
1
2
3
4
5
6
7
8
9
#与普通numpy数组相比,可以通过索引的方式选取Series中的单个或一组值
print(s[100])
print(s[[400, 500]])
100    a
100    c
dtype: object
400    d
500    e
dtype: object

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
s = pd.Series(np.array([1,2,3,4,5]), index=['a', 'b', 'c', 'd', 'e'])
print(s)
 
#对应元素求和
print(s+s)
 
#对应元素乘
print(s*3)
 
a    1
b    2
c    3
d    4
e    5
dtype: int64
a     2
b     4
c     6
d     8
e    10
dtype: int64
a     3
b     6
c     9
d    12
e    15
dtype: int64

Series中最重要的一个功能是:它会在算术运算中自动对齐不同索引的数据

Series 和多维数组的主要区别在于, Series 之间的操作会自动基于标签对齐数据。因此,不用顾及执行计算操作的 Series 是否有相同的标签。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
obj1 = pd.Series({"Ohio": 35000, "Oregon": 16000, "Texas": 71000, "Utah": 5000})
print(obj1)
obj2 = pd.Series({"California": np.nan, "Ohio": 35000, "Oregon": 16000, "Texas": 71000})
print(obj2)
print(obj1 + obj2)
Ohio      35000
Oregon    16000
Texas     71000
Utah       5000
dtype: int64
California        NaN
Ohio          35000.0
Oregon        16000.0
Texas         71000.0
dtype: float64
California         NaN
Ohio           70000.0
Oregon         32000.0
Texas         142000.0
Utah               NaN
dtype: float64

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
s = pd.Series(np.array([1,2,3,4,5]), index=['a', 'b', 'c', 'd', 'e'])
 
print(s[1:])
 
print(s[:-1])
 
print(s[1:] + s[:-1])
b    2
c    3
d    4
e    5
dtype: int64
a    1
b    2
c    3
d    4
dtype: int64
a    NaN
b    4.0
c    6.0
d    8.0
e    NaN
dtype: float64  
posted @   华小电  阅读(182)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示