目录
import numpy as np
import pandas as pd
s=pd.Series({'考号':'10182156','姓名':'王小丫','科目一':'97','科目二':'85'})
print(s)
>>> 考号 10182156
姓名 王小丫
科目一 97
科目二 85
dtype: object
1.按索引号(位置)访问
- 得到单个元素的值
#获取第一个元素和最后一个元素
#结果中不显示索引名
print('单一索引号访问:\n',s[0],s[-1])
>>> 单一索引号访问:
10182156 85
-
离散、切片得到索引名以及值组成的Series
索引号切片索引时,是左闭右开区间
#离散、切片获取的批量数据组成Series类型
#得到索引名以及值组成的Series
print('离散列表为索引号访问1:\n',s[[0,2]],sep='')
>>> 离散列表为索引号访问:
考号 10182156
科目一 97
dtype: object
print('切片索引号访问:\n',s[1:3],sep='')
>>> 切片索引号访问:
姓名 王小丫
科目一 97
dtype: object
2.按索引名访问
- 得到单个元素的值
print('单一索引名访问:\n',s['姓名'],sep='')
>>> 单一索引名访问:
王小丫
-
得到索引名以及值组成的Series
索引名切片索引时,左右均是闭区间
#切片头尾均可取到
print('离散列表为索引名访问2:\n',s[['姓名','科目二']],sep='')
>>> 离散列表为索引名访问:
姓名 王小丫
科目二 85
dtype: object
print('索引名切片访问:\n',s['考号':'科目一'],sep='')
>>> 索引名切片访问:
考号 10182156
姓名 王小丫
科目一 97
dtype: object
3.按条件访问(通过条件表达式)
dates=pd.date_range('20190708',periods=6)
s=pd.Series([112,37,43,58,44,48],index=dates)
print(s)
>>> 2019-07-08 112
2019-07-09 37
2019-07-10 43
2019-07-11 58
2019-07-12 44
2019-07-13 48
Freq: D, dtype: int64
#s.values<=50与s<=50对比
print(s.values<=50)#<class 'numpy.ndarray'>
>>> [False True True False True True]
print(s<=50)
>>> 2019-07-08 False
2019-07-09 True
2019-07-10 True
2019-07-11 False
2019-07-12 True
2019-07-13 True
Freq: D, dtype: bool
print(s[s.values<=50])
>>> 2019-07-09 37
2019-07-10 43
2019-07-12 44
2019-07-13 48
dtype: int64