第二章 索引
本章主要介绍Pandas数据结构中的各种索引方法
import numpy as np
import pandas as pd
df = pd.read_csv('data/table.csv',index_col='ID')
df.head()
一、单机索引
1. loc方法、iloc方法、[]操作符 (常用的三种)
# df.loc[要索引行的名称, 要索引的列的名称] (支持切片)
df.loc[1103] # 取ID为1103的行
df.loc[[1103, 1105]] # 取两行
df.loc[::-1]
df.loc[:, 'Height'] # 取列
# df.iloc与df.loc相似,i代表index,之按序号索引
注:请不要在行索引为浮点时使用[]操作符,因为在Series中的浮点[]并不是进行位置比较,而是值比较,非常特殊
# 在python语法中[]本身就是一种语法糖,所以[]索引与常规相似
s = pd.Series(df['Math'],index=df.index)
s[0:4]
s[lambda x: x.index[16::-6]]
s[s>80]
# 在dataframe中[]索引行是只能用对应的序号(0,1, ...),对列时可以是名称
# 但是可以用这种方式替代
row = df.index.get_loc(1102)
df[row:row+1]
2、布尔索引
布尔符号:’&’,’|’,’~’:分别代表和and,或or,取反not
loc和[]中相应位置都能使用布尔列表选择
df[(df['Gender']=='F')&(df['Address']=='street_2')].head()
isin方法 (is + in)感觉类似于bool方法
df[df['Address'].isin(['street_1','street_4'])&df['Physics'].isin(['A','A+'])]
3、快速标量索引
当只需要取一个元素时,at和iat方法能够提供更快的实现:
display(df.at[1101,'School'])
display(df.loc[1101,'School'])
display(df.iat[0,0])
display(df.iloc[0,0])
4、区间索引
原作这写的太。。。,不做解释了
pd.interval_range(start=0,end=5)
#closed参数可选'left''right''both''neither',默认左开右闭
pd.interval_range(start=0,periods=8,freq=5)
#periods参数控制区间个数,freq控制步长
math_interval = pd.cut(df['Math']