类似于列表的位置下标索引:
s=pd.Series(np.random.rand(10))
print(s)
0 0.969396
1 0.981999
2 0.064227
3 0.751186
4 0.923914
5 0.596080
6 0.179902
7 0.330775
8 0.048466
9 0.556931
dtype: float64
print(s[3]) #下标索引
0.7511855138771393
下标索引并不完全和列表一样:
print(s[-1]) #这里就报错了
Traceback (most recent call last):
File "<ipython-input-7-84238c3974a7>", line 1, in <module>
print(s[-1])
File "C:\Users\www12\Anaconda3\lib\site-packages\pandas\core\series.py", line 623, in __getitem__
result = self.index.get_value(self, key)
File "C:\Users\www12\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 2560, in get_value
tz=getattr(series.dtype, 'tz', None))
File "pandas/_libs/index.pyx", line 83, in pandas._libs.index.IndexEngine.get_value
File "pandas/_libs/index.pyx", line 91, in pandas._libs.index.IndexEngine.get_value
File "pandas/_libs/index.pyx", line 139, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/hashtable_class_helper.pxi", line 811, in pandas._libs.hashtable.Int64HashTable.get_item
File "pandas/_libs/hashtable_class_helper.pxi", line 817, in pandas._libs.hashtable.Int64HashTable.get_item
KeyError: -1
标签索引:
s=pd.Series(np.random.rand(6),index=['a','b','c','d','e','f'])
print(s)
a 0.635180
b 0.471829
c 0.859320
d 0.505514
e 0.500021
f 0.299368
dtype: float64
方法类似下标索引,用[]表示,内容写上index,注意index是字符串
print(s['a'])
0.6351798913911209
print(s[['a','b']])
a 0.635180
b 0.471829
dtype: float64
多个标签索引用[[]]表示,[]表示一个列表
标签索引可以不按照index的顺序来,结果会生成新的数组
切片:
print(s[1:5]) #下标,左闭右开
b 0.471829
c 0.859320
d 0.505514
e 0.500021
dtype: float64
print(s['a':'c']) #标签,左闭右闭
a 0.635180
b 0.471829
c 0.859320
dtype: float64
布尔索引
s=pd.Series(np.random.rand(6)*100,index=['a','b','c','d','e','f'])
print(s)
a 61.803796
b 45.965736
c 89.229410
d 61.375478
e 20.890655
f 8.225829
dtype: float64
s[4]=None
bs1=s>50
print(bs1) #得到一个布尔型的数组
a True
b False
c True
d True
e False
f False
dtype: bool
bs2=s.isnull() #判断是否为空值
bs3=s.notnull() #判断是否不是空值
print(bs2)
print(bs3)
a False
b False
c False
d False
e True
f False
dtype: bool
a True
b True
c True
d True
e False
f True
dtype: bool
以上就是Series的索引方法,应当注意下标索引和标签索引和切片的区别。