pandas库中series数据结构的常用方法

文章初衷

series,又称序列。是pandas库中的一种常用数据结构。为了提高工作效率,笔者总结了该数据结构的一些常用使用方法,尽量使读者只需看本篇文章即可无障碍掌握这个叫series的数据结构的用法。

案例引入包

import numpy as np
import pandas as pd

pandas.core.series.Series的代码组成

pd.Series(data,index,dtype,name)

data:数据可以为list()、np.array()、dict()

index:索引,其长度必须与数据长度相同。

dtype:数据类型。

name:pandas.Series这个数据结构的名称。

pandas.core.series.Series的常用创建方式

方式1

s1 = pd.Series([1.2, 3.2, 1.2, 2.4, 3.3])
0    1.2
1    3.2
2    1.2
3    2.0
4    4.0
5    3.3
dtype: float64

方式2

s2 = pd.Series([1.2, 3.2, 1.2, 2.4, 3.3], index=['a', 'b', 'c', 'd', 'e'], name='series2')
a    1.2
b    3.2
c    1.2
d    2.4
e    3.3
Name: series2, dtype: float64

方式3

s3 = pd.Series(np.array([1.2, 3.2, 1.2, 2.4, 3.3]), index=['a', 'b', 'c', 'd', 'e'])
a    1.2
b    3.2
c    1.2
d    2.4
e    3.3
dtype: float64

方式4

s4 = pd.Series({'北京': 12, '大连': 23, '四川': 22})
北京    12
大连    23
四川    22
dtype: int64

方式N

# 发挥你的想象,在满足结构规则的条件下,创建序列。

pandas.core.series.Series结构中获取全部值

返回的是一个numpy array

s1.values
array([1.2, 3.2, 1.2, 2.4, 3.3])

pandas.core.series.Series结构中获取全部索引

返回类型:pandas.core.indexes.range.RangeIndex 左闭右开

s1.index
RangeIndex(start=0, stop=5, step=1)

返回类型:list()

s1.index.tolist()
[0, 1, 2, 3, 4]

返回类型:pandas.core.indexes.base.Index

s4.index
Index(['北京', '大连', '四川'], dtype='object')

返回类型:list()

s4.index.tolist()
['北京', '大连', '四川']

pandas.core.series.Series结构中各种信息的获取

获取数据类型

s1.dtype
dtype('float64')

获取维度

s1.ndim
1

获取形状

s1.shape
(5,)

获取元素个数

s1.size
5

获取总结信息

s1.info
<bound method Series.info of 0    1.2
1    3.2
2    1.2
3    2.4
4    3.3
dtype: float64>
s1.info()
<class 'pandas.core.series.Series'>
RangeIndex: 5 entries, 0 to 4
Series name: None
Non-Null Count  Dtype  
--------------  -----  
5 non-null      float64
dtypes: float64(1)
memory usage: 168.0 bytes

pandas.core.series.Series结构的切片

对于index为排序数字的,左闭右开。

s1[0:3]
0    1.2
1    3.2
2    1.2
dtype: float64

对于index为非排序数字的,左闭右闭。

s4['北京':'大连']
北京    12
大连    23
dtype: int64
posted @ 2023-01-02 16:09  顺心无忧  阅读(137)  评论(0编辑  收藏  举报