Series数据结构

1. 创建Series对象

pd.Series 是 Pandas 库中用于创建一维数组的函数

data: 可以是多种数据类型,如列表、元组、字典、NumPy 数组等

index: 可以是列表、元组等可迭代对象,其长度需要和 data 的长度一致。如果不指定 index,默认会使用从 0 开始的整数作为索引

1
2
3
4
5
s_data = pd.Series(
data=np.arange(1,4),
index=list("abc")
)
s_data

输出

1
2
3
4
a    1
b 2
c 3
dtype: int32

2. Series对象访问

1
2
3
s_data.iloc[0]
s_data.loc['a']
s_data['a']

输出

1
2
3
1
1
1

3. 获取index与value

1
2
3
4
# 获取索引
s_data.index
# 获取值
s_data.values

输出

1
2
Index(['a', 'b', 'c'], dtype='object')
array([1, 2, 3])

4. 将index与value转成列表

1
2
3
4
# 将索引转换成列表
s_data.index.tolist()
# 将数据转换成列表
s_data.values.tolist()

输出

1
2
['a', 'b', 'c']
[1, 2, 3]

5. Series对象访问

1
2
for item in s_data.items():
print(item)

输出

1
2
3
('a', 1)
('b', 2)
('c', 3)