Series索引
通过位置下标
# 通过位置下标
import numpy as np
import pandas as pd
s = pd.Series(np.random.rand(5))
print(s)
print('-------------------')
print(s[0],type(s[0]),s[0].dtype)
print(float(s[0]),type(float(s[0])))
# 输出结果为numpy.float格式
# 可以通过float() 函数转换为 Python float格式
# 注意这里不能用s[-1]进行索引
结果如下:
0 0.985720
1 0.610424
2 0.794172
3 0.521456
4 0.233943
dtype: float64
-------------------
0.9857204496573357 <class 'numpy.float64'> float64
0.9857204496573357 <class 'float'>
通过标签索引
s = pd.Series(np.random.rand(5),index = ['a','b','c','d','e'])
print(s)
print('----------------------')
print(s['a'],type(s['a']),s['a'].dtype)
# 方法类似下标索引,用[]表示,内写上index,注意index是字符串
print('----------------------')
s1 = s[['a','b','e']]
print(s1,type(s1))
# 如果需要选择多个标签的值,用[[]]表示,相当于[]中包含一个列表
# 多标签索引结果是新的数组
结果如下:
a 0.975143
b 0.572161
c 0.185438
d 0.650765
e 0.496250
dtype: float64
----------------------
0.9751425544700743 <class 'numpy.float64'> float64
----------------------
a 0.975143
b 0.572161
e 0.496250
dtype: float64 <class 'pandas.core.series.Series'>
通过切片索引
# 通过切片索引
s1 = pd.Series(np.random.rand(5))
s2 = pd.Series(np.random.rand(5),index = ['a','b','c','d','e'])
print(s1)
print('-------------------')
print(s1[1:4],s1[4])
print('-------------------')
print(s2['a':'c'],s2['c']) # 用index做切片是末端包含
print('-------------------')
print(s2[:-1])
print(s2[::2])
# 下标索引做切片,和list写法一样
结果如下:
0 0.103141
1 0.569733
2 0.494048
3 0.984490
4 0.815918
dtype: float64
-------------------
1 0.569733
2 0.494048
3 0.984490
dtype: float64 0.8159181513741175
-------------------
a 0.719097
b 0.993512
c 0.110926
dtype: float64 0.11092592872359519
-------------------
a 0.719097
b 0.993512
c 0.110926
d 0.186139
dtype: float64
a 0.719097
c 0.110926
e 0.175417
dtype: float64
通过布尔型索引
s = pd.Series(np.random.rand(3)*100)
s[4] = None # 添加一个空值
print(s)
bs1 = s > 50
bs2 =s.isnull()
bs3 = s.notnull()
print('-----------------')
print(bs1,type(bs1),bs1.dtype)
print('-----------------')
print(bs2,type(bs2),bs2.dtype)
print('-----------------')
print(bs3,type(bs3),bs3.dtype)
# 数组做判断之后,返回的是一个由布尔值组成的新的数组
# .isnull()/.notnull() 判断是否为空值(None为空值,NaN代表有问题的数值,都会识别为空值)
print('-----------------')
print(s[s>50])
print('-----------------')
print(s[bs3])
# 布尔型索引方法:用[判断条件]表示,其中判断条件可以是一个语句,或一个布尔型数组
结果如下:
0 58.6051
1 11.7526
2 60.0929
4 None
dtype: object
-----------------
0 True
1 False
2 True
4 False
dtype: bool <class 'pandas.core.series.Series'> bool
-----------------
0 False
1 False
2 False
4 True
dtype: bool <class 'pandas.core.series.Series'> bool
-----------------
0 True
1 True
2 True
4 False
dtype: bool <class 'pandas.core.series.Series'> bool
-----------------
0 58.6051
2 60.0929
dtype: object
-----------------
0 58.6051
1 11.7526
2 60.0929
dtype: object