import pandas as pd
import numpy as np
.iloc 选择定位数据
df = pd.read_csv('data/sample_data.csv',index_col=0)
df

iloc基于数值索引选择数据
选择索引为3的一行数据,对应的是行索引名称为Penelope的哪一行,返回的是Seires
df.iloc[3]
state AL
color white
food Apple
age 4
height 80
score 3.3
Name: Penelope, dtype: object
上边的例子是返回Series,下边的列子是返回DataFrame形式,如下
df.iloc[[3]]

选择多行
df.iloc[[5,3,2]]

切片选择多行
df.iloc[3:5]

df.iloc[2:]

df.iloc[1:4:2]

选择行列
- 多行多列
df.iloc[[2,5],[0,3]]

- 行切片,多列
df.iloc[1:5,[0,3,4]]

- 行列切片选择
df.iloc[2:5,1:4]

- 选择单元格
df.iloc[2,5]
9.0
- 选择所有行,1列,以series返回
df.iloc[:,5]
Jane 4.6
Niko 8.3
Aaron 9.0
Penelope 3.3
Dean 1.8
Christina 9.5
Cornelia 2.2
Name: score, dtype: float64
- 选择所有行,1列以DataFrame返回
df.iloc[:,[5]]

- 选单行所有列,以series返回
df.iloc[1,:]
state TX
color green
food Lamb
age 2
height 70
score 8.3
Name: Niko, dtype: object
- 选择单行所有列,以DataFrame返回
df.iloc[[1],:]

说明,pandas有.ix方法,在使用python进行数据分析第一版中有介绍,但是该该方法已经过时,尽量不要再用
Series 中通用 .iloc .loc
s=df['food']
s
Jane Steak
Niko Lamb
Aaron Mango
Penelope Apple
Dean Cheese
Christina Melon
Cornelia Beans
Name: food, dtype: object
type(s)
pandas.core.series.Series
loc 使用
s.loc['Dean']
'Cheese'
s.iloc[3]
'Apple'
s.loc[:]
Jane Steak
Niko Lamb
Aaron Mango
Penelope Apple
Dean Cheese
Christina Melon
Cornelia Beans
Name: food, dtype: object
s.loc['Niko':'Dean']
Niko Lamb
Aaron Mango
Penelope Apple
Dean Cheese
Name: food, dtype: object
s.loc['Dean':]
Dean Cheese
Christina Melon
Cornelia Beans
Name: food, dtype: object
s.loc[['Niko','Dean']]
Niko Lamb
Dean Cheese
Name: food, dtype: object
iloc 使用
s.iloc[2]
'Mango'
s.iloc[[2,3]]
Aaron Mango
Penelope Apple
Name: food, dtype: object
s.iloc[1:3]
Niko Lamb
Aaron Mango
Name: food, dtype: object
s.iloc[1:]
Niko Lamb
Aaron Mango
Penelope Apple
Dean Cheese
Christina Melon
Cornelia Beans
Name: food, dtype: object
网友评论