3.3 数据取值与选择
Series
将Series看作字典
import pandas as pd
data = pd.Series([0.25, 0.5, 0.75, 1], index=['a', 'b', 'c', 'd'])
data
a 0.25 b 0.50 c 0.75 d 1.00 dtype: float64
# 键引用
data['b']
0.5
'a' in data
True
data.keys()
Index(['a', 'b', 'c', 'd'], dtype='object')
list(data.items())
[('a', 0.25), ('b', 0.5), ('c', 0.75), ('d', 1.0)]
# 用字典方式添加新数据元素
data['e'] = 1.25
data
a 0.25 b 0.50 c 0.75 d 1.00 e 1.25 dtype: float64
将Series看作一维数组
# 将显式索引作为切片,最后的索引也会切片进来
data['a':'c']
a 0.25 b 0.50 c 0.75 dtype: float64
# 将隐式整数索引作为切片
data[0:2]
a 0.25 b 0.50 dtype: float64
# 掩码
data[(data > 0.3) & (data < 0.8)]
b 0.50 c 0.75 dtype: float64
# 花哨的索引
data[['a', 'e']]
a 0.25 e 1.25 dtype: float64
将显式索引作为切片,最后的索引也会切片进来。如果显式的索引本身也是数字,就会和隐式数字索引混淆,因此有索引器方法。
data = pd.Series(['a', 'b', 'c'], index=[1, 3, 5])
data
1 a 3 b 5 c dtype: object
# 取值操作是显式索引
data[1]
'a&#