欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Pandas中的loc與iloc區(qū)別與用法小結(jié)

 更新時(shí)間:2024年01月17日 10:45:16   作者:獨(dú)影月下酌酒  
loc函數(shù):通過(guò)行索引 “Index” 中的具體值來(lái)取行數(shù)據(jù)(如取"Index"為"A"的行)而iloc函數(shù):通過(guò)行號(hào)來(lái)取行數(shù)據(jù)(如取第二行的數(shù)據(jù)),這篇文章介紹Pandas中的loc與iloc區(qū)別與用法,感興趣的朋友一起看看吧

1.基本簡(jiǎn)介

1.1 loc與iloc基本含義

loc函數(shù):通過(guò)行索引 “Index” 中的具體值來(lái)取行數(shù)據(jù)(如取"Index"為"A"的行

iloc函數(shù):通過(guò)行號(hào)來(lái)取行數(shù)據(jù)(如取第二行的數(shù)據(jù)

注:loc是location的意思,iloc中的i是integer的意思,僅接受整數(shù)作為參數(shù)。

1.2 loc與iloc的區(qū)別

官網(wǎng)解釋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

二者的區(qū)別(傳入?yún)?shù)的不同):

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

2.使用方法

2.0 數(shù)據(jù)準(zhǔn)備

# 導(dǎo)包
import numpy as np
import pandas as pd
#創(chuàng)建Dataframe
data=pd.DataFrame(np.arange(25).reshape(5,5),index=list('abcde'),columns=list('ABCDE'))

2.1 使用loc與iloc提取行數(shù)據(jù)

需求:獲取索引為’a’的行數(shù)據(jù)

# loc的方式
data.loc['a']
# 輸出結(jié)果:
A    0
B    1
C    2
D    3
E    4
Name: a, dtype: int32
# iloc的方式:索引為a即為第一行數(shù)據(jù)
data.iloc[0]
# 輸出結(jié)果:
A    0
B    1
C    2
D    3
E    4
Name: a, dtype: int32
# iloc按照切片方式處理
data.iloc[:1]

2.2 使用loc與iloc提取列數(shù)據(jù)

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

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

# 'A'列的數(shù)據(jù)即為第0列的數(shù)據(jù)
data.iloc[:,[0]]

2.3 使用loc與iloc提取指定行、列的數(shù)據(jù)

需求: 提取index為’a’,‘b’,列名為’A’,'B’中的數(shù)據(jù)

# 提取index為'a','b',列名為'A','B'中的數(shù)據(jù)
data.loc[['a','b'],['A','B']]

# 提取第0、1行,第0、1列中的數(shù)據(jù)
data.iloc[[0,1],[0,1]]

2.4 使用loc與iloc提取所有數(shù)據(jù)

需求:提取所有數(shù)據(jù)

data.loc[:,:]

data.iloc[:,:]

2.5 使用loc根據(jù)某個(gè)條件來(lái)提取數(shù)據(jù)所在的行

需求1:提取A列中數(shù)值為0的所在行數(shù)據(jù)

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

需求2:提取A列中數(shù)字為0,且B列中數(shù)值為1所在行的數(shù)據(jù)

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

# 其他實(shí)現(xiàn)方式:
data[data['A']==0] #dataframe用法
data[data['A'].isin([0])] #isin函數(shù)
data[(data['A']==0)&(data['B']==2)] #dataframe用法
data[(data['A'].isin([0]))&(data['B'].isin([2]))] #isin函數(shù)
Out[15]: 
   A  B  C  D  E
a  0  1  2  3  4

3. 總結(jié)

對(duì)于loc選取行列數(shù)據(jù):

  • 行根據(jù)行標(biāo)簽,也就是索引篩選,列根據(jù)列標(biāo)簽,列名篩選
  • 如果選取的是所有行或者所有列,可以用:代替
  • 行標(biāo)簽選取的時(shí)候,兩端都包含,比如[0:5]指的是0,1,2,3,4,5

對(duì)于iloc選取行列數(shù)據(jù):

  • iloc基于位置索引,簡(jiǎn)言之,就是第幾行第幾列,只不過(guò)這里的行列都是從0開(kāi)始的。
  • iloc的0:X中不包括X,只能到X-1.

參考鏈接:

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

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

到此這篇關(guān)于Pandas中的loc與iloc區(qū)別與用法小結(jié)的文章就介紹到這了,更多相關(guān)Pandas中的loc與iloc內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論