詳談Pandas中iloc和loc以及ix的區(qū)別
Pandas庫中有iloc和loc以及ix可以用來索引數(shù)據(jù),抽取數(shù)據(jù)。但是方法一多也容易造成混淆。下面將一一來結(jié)合代碼說清其中的區(qū)別。
1. iloc和loc的區(qū)別:
iloc主要使用數(shù)字來索引數(shù)據(jù),而不能使用字符型的標簽來索引數(shù)據(jù)。而loc則剛好相反,只能使用字符型標簽來索引數(shù)據(jù),不能使用數(shù)字來索引數(shù)據(jù),不過有特殊情況,當數(shù)據(jù)框dataframe的行標簽或者列標簽為數(shù)字,loc就可以來其來索引。
好,先上代碼,先上行標簽和列標簽都為數(shù)字的情況。
import pandas as pd import numpy as np a = np.arange(12).reshape(3,4) print a >>> [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] df = pd.DataFrame(a) print df >>> 0 1 2 3 0 0 1 2 3 1 4 5 6 7 2 8 9 10 11 print df.loc[0] >>> 0 0 1 1 2 2 3 3 Name: 0, dtype: int32 print df.iloc[0] 0 0 1 1 2 2 3 3 Name: 0, dtype: int32 print df.loc[:,[0,3]] 0 3 0 0 3 1 4 7 2 8 11 print df.iloc[:,[0,3]] 0 3 0 0 3 1 4 7 2 8 11
接下來是把行標簽[0, 1, 2]改成['a', 'b', 'c'],則成這樣了。
df.index = ['a','b','c'] print df >>> 0 1 2 3 a 0 1 2 3 b 4 5 6 7 c 8 9 10 11 print df.loc[0] # TypeError: cannot do label indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [0] of <type 'int'> print df.iloc[0] >>> 0 0 1 1 2 2 3 3 Name: a, dtype: int32 print df.iloc['a'] # TypeError: cannot do positional indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [a] of <type 'str'> print df.loc['a'] # 正確 >>> 0 0 1 1 2 2 3 3 Name: a, dtype: int32
同樣地,把列標簽[0, 1, 2, 3]改成['A', 'B, 'C', 'D'],則成這樣了。
df.columns = ['A','B','C','D'] print df >>> A B C D a 0 1 2 3 b 4 5 6 7 c 8 9 10 11 print df.loc[:,'A'] >>> a 0 b 4 c 8 Name: A, dtype: int32 print df.iloc[:,'A'] # ValueError: Location based indexing can only have [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array] types
2.ix是一種混合索引,字符型標簽和整型數(shù)據(jù)索引都可以。
print df.ix[0] >>> A 0 B 1 C 2 D 3 Name: a, dtype: int32 print df.ix['a'] >>> A 0 B 1 C 2 D 3 Name: a, dtype: int32 print df.ix[:,0] >>> a 0 b 4 c 8 Name: A, dtype: int32 print df.ix[:,'A'] >>> a 0 b 4 c 8 Name: A, dtype: int32
以上這篇詳談Pandas中iloc和loc以及ix的區(qū)別就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
- Python Pandas數(shù)據(jù)分析之iloc和loc的用法詳解
- 聊聊Python pandas 中l(wèi)oc函數(shù)的使用,及跟iloc的區(qū)別說明
- python選取特定列 pandas iloc,loc,icol的使用詳解(列切片及行切片)
- 一文秒懂pandas中iloc()函數(shù)
- 利用Pandas讀取某列某行數(shù)據(jù)之loc和iloc用法總結(jié)
- Pandas中的loc與iloc區(qū)別與用法小結(jié)
- 對pandas中iloc,loc取數(shù)據(jù)差別及按條件取值的方法詳解
- Python?Pandas中l(wèi)oc和iloc函數(shù)的基本用法示例
- python中pandas庫的iloc函數(shù)用法解析
- Pandas索引器 loc 和 iloc 比較及代碼示例
相關(guān)文章
Python中使用多進程來實現(xiàn)并行處理的方法小結(jié)
本篇文章主要介紹了Python中使用多進程來實現(xiàn)并行處理的方法小結(jié),具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-08-08
Python?Playwright庫從入門到實戰(zhàn)教程
Playwright是一個用于自動化Web瀏覽器測試的庫,它提供了一種高級的API來模擬用戶行為,無論是在自動化測試、爬蟲還是生成復雜的用戶交互場景中都非常有用,這篇文章主要介紹了Python?Playwright庫從入門到實戰(zhàn)的相關(guān)資料,需要的朋友可以參考下2025-12-12

