Series索引、切片

本文详细介绍了Series的索引和切片操作,包括位置索引从0开始,标签索引通过index名称,切片时index是末端包含,而位置索引切片遵循前包后不包规则。此外,还提到了布尔型索引,如使用.isnull()和.notnull()判断空值,并通过布尔数组进行索引过滤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一. Series 位置索引
位置索引,从0开始数,[0]是series第一个数,[1]是series第二个数
series不能[-1]定位索引

In [1]:s = pd.Series(np.random.rand(10))
Out[1]:
0    0.773893
1    0.186367
2    0.091893
3    0.778826
4    0.831756
5    0.537671
6    0.874914
7    0.845950
8    0.045002
9    0.362285
dtype: float64

In [2]:s[0]
Out[2]:0.773893

In [3]:s[6]
Out[3]:0.537671

二. Series 标签索引
方法类似位置索引,用[]表示,内写上index,注意index是字符串
如果需要选择多个标签的值,用[[]]来表示(相当于[]中包含一个列表)

In [1]:s = pd.Series(np.random.rand(5), index = ['a','b','c','d','e'])
Out[1]:
a    0.714630
b    0.213957
c    0.172188
d    0.972158
e    0.875175
dtype: float64

In [2]:s['a']
Out[2]:0.714630383451

In [3]:s[['a','b','e']]
Out[3]:
a    0.714630
b    0.213957
e    0.875175

三. Series 切片索引
用index做切片是末端包含

In [1]:s1 = pd.Series(np.random.rand(5), index = ['a','b','c','d','e'])
Out[1]:
a    0.714630
b    0.213957
c    0.172188
d    0.972158
e    0.875175
dtype: float64

In [2]:s1['a':'c']
Out[2]:
a    0.714630
b    0.213957
c    0.172188
dtype: float64

In [3]:s1['c']
Out[3]:0.172188

位置索引做切片,和list写法一样,切片是前包后不包,意思是前端包含,后端不包含

In [1]:s2 = pd.Series(np.random.rand(5))
Out[1]:
0    0.924575
1    0.988654
2    0.426333
3    0.216504
4    0.453570
dtype: float64

In [2]:s2[1:4]
Out[2]:
0    0.924575
1    0.988654
2    0.426333
3    0.216504
dtype: float64

In [3]:s2[4]
Out[3]: 0.453570

四. Series 布尔型索引
数组做判断之后,返回的是一个由布尔值组成的新的数组
.isnull() / .notnull() 判断是否为空值 (None代表空值,NaN代表有问题的数值,两个都会识别为空值)
布尔型索引方法:用[判断条件]表示,其中判断条件可以是 一个语句,或者是 一个布尔型数组!

In [1]:s = pd.Series(np.random.rand(3)*100)
In [2]:s[4] = None  # 添加一个空值
Out[2]:
0    2.03802
1    40.3989
2    25.2001
4       None
dtype: object

In [3]:bs1 = s > 50
In [4]:bs1
Out[4]:
0    False
1    False
2    False
4    False
dtype: bool

In [5]:bs2 = s.isnull()
In [6]:bs2
Out[6]:
0    False
1    False
2    False
4     True
dtype: bool

In [7]:bs3 = s.notnull()
In [8]:bs3
Out[8]:
0     True
1     True
2     True
4    False
dtype: bool 

In [9]:s[s > 50]
Out[9]:
Series([], dtype: object)

In [10]:s[bs3]
Out[10]:
0    2.03802
1    40.3989
2    25.2001
dtype: object
# 布尔型索引方法:用[判断条件]表示,其中判断条件可以是 一个语句,或者是 一个布尔型数组!

Dataframe 索引、切片及技巧 https://blog.youkuaiyun.com/weixin_43291997/article/details/83213497

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值