Pandas中的loc与iloc用法详解

1.基本简介

1.1 loc与iloc基本含义

loc函数:通过行索引 “Index” 中的具体值来取行数据(如取"Index"为"A"的行

iloc函数:通过行号来取行数据(如取第二行的数据

注:loc是location的意思,iloc中的i是integer的意思,仅接受整数作为参数。

1.2 loc与iloc的区别

官网解释DataFrame中的loc与iloc:

Purely integer-location based indexing for selection by position. –iloc

Access a group of rows and columns by label(s) or a boolean array. –loc

二者的区别(传入参数的不同):

loc works on labels in the index.
iloc works on the positions in the index (so it only takes integers).

2.使用方法

2.0 数据准备

# 导包
import numpy as np
import pandas as pd
#创建Dataframe
data=pd.DataFrame(np.arange(25).reshape(5,5),index=list('abcde'),columns=list('ABCDE'))

2.1 使用loc与iloc提取行数据

需求:获取索引为’a’的行数据

# loc的方式
data.loc['a']

# 输出结果:
A    0
B    1
C    2
D    3
E    4
Name: a, dtype: int32

# iloc的方式:索引为a即为第一行数据
data.iloc[0]
# 输出结果:
A    0
B    1
C    2
D    3
E    4
Name: a, dtype: int32
# iloc按照切片方式处理
data.iloc[:1]

2.2 使用loc与iloc提取列数据

需求:取’A’列所有行,多取几列格式为 data.loc[:,[‘A’,‘B’]],data.iloc[:,[0,1]]

data.loc[:,['A']]

# 'A'列的数据即为第0列的数据
data.iloc[:,[0]]

2.3 使用loc与iloc提取指定行、列的数据

#提取index为’a’,‘b’,列名为’A’,'B’中的数据

# 提取index为'a','b',列名为'A','B'中的数据
data.loc[['a','b'],['A','B']]

# 提取第0、1行,第0、1列中的数据
data.iloc[[0,1],[0,1]]

2.4 使用loc与iloc提取所有数据

需求:提取所有数据

data.loc[:,:]

data.iloc[:,:]

2.5 使用loc根据某个条件来提取数据所在的行

需求1:提取A列中数值为0的所在行数据

data.loc[data['A']==0]

需求2:提取A列中数字为0,且B列中数值为1所在行的数据

data.loc[(data['A']==0) & (data['B']==1)]

# 其他实现方式:
data[data['A']==0] #dataframe用法
data[data['A'].isin([0])] #isin函数
data[(data['A']==0)&(data['B']==2)] #dataframe用法
data[(data['A'].isin([0]))&(data['B'].isin([2]))] #isin函数
 
Out[15]: 
   A  B  C  D  E
a  0  1  2  3  4

3. 总结

对于loc选取行列数据:

  1. 行根据行标签,也就是索引筛选,列根据列标签,列名筛选
  2. 如果选取的是所有行或者所有列,可以用:代替
  3. 行标签选取的时候,两端都包含,比如[0:5]指的是0,1,2,3,4,5

对于iloc选取行列数据:

  1. iloc基于位置索引,简言之,就是第几行第几列,只不过这里的行列都是从0开始的。
  2. iloc的0:X中不包括X,只能到X-1.

参考链接:

1.https://blog.csdn.net/W_weiying/article/details/81411257

2.https://zhuanlan.zhihu.com/p/129898162

来源:独影月下酌酒

物联沃分享整理
物联沃-IOTWORD物联网 » Pandas中的loc与iloc用法详解

发表评论