第二章 索引
- 1.单级索引
- 2.多级索引
- 3.索引设定
- 4.常用索引型函数
- 5.重复元素处理
- 6.抽样函数
`#### 1 单级索引
loc方法、iloc方法、操作符
最常用的索引方法可能就是这三类,其中iloc表示位置索引,loc表示标签索引,[]也具有很大的便利性,各具有特点
先建立一个数据集
import numpy as np
import pandas as pd
df = pd.read_csv('data/table.csv',index_col='ID')
df.head()
单行索引
df.loc[1103]
多行索引
df.loc[[1102,2304]]
单列索引
df.loc[:,'Height'].head()
多列索引
df.loc[:,['Height','Math']].head()
联合索引
df.loc[1102:2401:3,'Height':'Math'].head()
函数式索引
df.loc[lambda x:x['Gender']=='M'].head()
def f(x):
return [1101,1103]
df.loc[f]
布尔索引
df.loc[df['Address'].isin(['street_7','street_4'])].head()
df.loc[[True if i[-1]=='4' or i[-1]=='7' else False for i in df['Address'].values]].head()
iloc方法:
单行索引
df.iloc[3]
多行索引
df.iloc[3:5]
单列索引
df.iloc[:,3].head()
多列索引
df.iloc[:,7::-2].head()
混合索引
df.iloc[3::4,7::-2].head()
函数式索引
df.iloc[lambda x:[3]].head()
[]操作符
单元素索引
s = pd.Series(df['Math'],index=df.index)
s[1101]
多行索引
s[0:4]
函数式索引
s[lambda x: x.index[16::-6]]
布尔索引
s[s>80]
Dataframe的[]操作
单行索引
df[1:2]
row = df.index.get_loc(1102)
df[row:row+1]
多行索引
df[3:5]
单列索引
df['School'].head()
多列索引
df[['School','Math']].head()
函数式索引
df[lambda x:['Math','Physics']].head()
布尔索引
df[df['Gender']=='F'].head()
2.布尔索引
1.布尔符号:‘&’,‘|’,’~‘:分别代表and or not
df[(df['Math']>85)|(df['Address']=='street_7')].head()
df[~((df['Math']>75)|(df['Address&#