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

data=pd.DataFrame(np.arange(25).reshape(5,5),index=list('abcde'),columns=list('ABCDE'))

Pandas中的loc与iloc用法详解

2.1 使用loc与iloc提取行数据

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


data.loc['a']

A    0
B    1
C    2
D    3
E    4
Name: a, dtype: int32

data.iloc[0]

A    0
B    1
C    2
D    3
E    4
Name: a, dtype: int32

data.iloc[:1]

Pandas中的loc与iloc用法详解

2.2 使用loc与iloc提取列数据

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

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

Pandas中的loc与iloc用法详解

data.iloc[:,[0]]

Pandas中的loc与iloc用法详解

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

需求: 提取index为’a’,’b’,列名为’A’,’B’中的数据


data.loc[['a','b'],['A','B']]

Pandas中的loc与iloc用法详解

data.iloc[[0,1],[0,1]]

Pandas中的loc与iloc用法详解

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

需求:提取所有数据

data.loc[:,:]

Pandas中的loc与iloc用法详解
data.iloc[:,:]

Pandas中的loc与iloc用法详解

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

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

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

Pandas中的loc与iloc用法详解

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

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

Pandas中的loc与iloc用法详解

data[data['A']==0]
data[data['A'].isin([0])]
data[(data['A']==0)&(data['B']==2)]
data[(data['A'].isin([0]))&(data['B'].isin([2]))]

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-

Pandas中的loc与iloc用法详解

参考链接:

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

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

Original: https://blog.csdn.net/weixin_44852067/article/details/122301685
Author: 独影月下酌酒
Title: Pandas中的loc与iloc用法详解

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/724122/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球