Pandas中的loc與iloc區(qū)別與用法小結
1.基本簡介
1.1 loc與iloc基本含義
loc函數(shù):通過行索引 “Index” 中的具體值來取行數(shù)據(jù)(如取"Index"為"A"的行)
iloc函數(shù):通過行號來取行數(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ù)準備
# 導包
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'] # 輸出結果: A 0 B 1 C 2 D 3 E 4 Name: a, dtype: int32 # iloc的方式:索引為a即為第一行數(shù)據(jù) 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提取列數(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ù)某個條件來提取數(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)]

# 其他實現(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. 總結
對于loc選取行列數(shù)據(jù):
- 行根據(jù)行標簽,也就是索引篩選,列根據(jù)列標簽,列名篩選
- 如果選取的是所有行或者所有列,可以用:代替
- 行標簽選取的時候,兩端都包含,比如[0:5]指的是0,1,2,3,4,5
對于iloc選取行列數(shù)據(jù):
- iloc基于位置索引,簡言之,就是第幾行第幾列,只不過這里的行列都是從0開始的。
- iloc的0:X中不包括X,只能到X-1.

參考鏈接:
1.https://blog.csdn.net/W_weiying/article/details/81411257
2.https://zhuanlan.zhihu.com/p/129898162
到此這篇關于Pandas中的loc與iloc區(qū)別與用法小結的文章就介紹到這了,更多相關Pandas中的loc與iloc內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- Python pandas中的iloc使用小結
- pandas loc與iloc用法及區(qū)別
- python中pandas庫的iloc函數(shù)用法解析
- 一文秒懂pandas中iloc()函數(shù)
- Pandas庫中iloc[]函數(shù)的使用方法
- pandas loc iloc ix用法詳細分析
- 利用Pandas讀取某列某行數(shù)據(jù)之loc和iloc用法總結
- Python Pandas數(shù)據(jù)分析之iloc和loc的用法詳解
- python pandas中索引函數(shù)loc和iloc的區(qū)別分析
- pandas中.loc和.iloc以及.at和.iat的區(qū)別說明
- pandas中iloc函數(shù)的具體實現(xiàn)
相關文章
Pandas篩選DataFrame含有空值的數(shù)據(jù)行的實現(xiàn)
本文主要介紹了Pandas篩選DataFrame含有空值的數(shù)據(jù)行的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-07-07

