【基本工具】S02E07 Series对象的数据选取方法

# 0.本集概览

1.类比字典，按照键-值的方法来进行取值
2.类比数组，采用分片、条件掩码和花哨索引来取值
3.采用索引器使得数值型索引的取值更清晰

# 1.类比字典，按键值方式获取数据

import pandas as pd

data = pd.Series([0.25,0.5,0.75,1.0]
,index=['a','b','c','d'])
print(data['c'])             #通过键来获取字典的值
print('a' in data)           #判断键是否存在
print(data.keys())           #获取键的列表
print(list(data.items()))    #获取键值对的列表

0.75
True
Index(['a', 'b', 'c', 'd'], dtype='object')
[('a', 0.25), ('b', 0.5), ('c', 0.75), ('d', 1.0)]

import pandas as pd

data = pd.Series([0.25,0.5,0.75,1.0]
,index=['a','b','c','d'])
data['e'] = 1.25
print(data)

a    0.25
b    0.50
c    0.75
d    1.00
e    1.25
dtype: float64

# 2.类比NumPy，采用分片、掩码、花哨索引

Series还可以看做是一维数组对象，那么我们再次类比一下NumPy数据类型，类比采用NumPy中的分片索引、掩码以及花哨索引方法。

import pandas as pd

data = pd.Series([0.25,0.5,0.75,1.0]
,index=['a','b','c','d'])

print(data['a':'c'])
print(data[0:2])

a    0.25
b    0.50
c    0.75
dtype: float64

a    0.25
b    0.50
dtype: float64

import pandas as pd

data = pd.Series([0.25,0.5,0.75,1.0]
,index=['a','b','c','d'])
print(data[(data > 0.2) & (data < 0.6)])

a    0.25
b    0.50
dtype: float64

`
import pandas as pd

data = pd.Series([0.25,0.5,0.75,1.0]
,index=['a','b','c','d'])