一開始自學(xué)Python的numpy、pandas時(shí)候,索引和切片把我都給弄暈了,特別是numpy的切片索引、布爾索引和花式索引,簡(jiǎn)直就是大亂斗。但是最近由于版本的問(wèn)題,從之前的Python2.7改用Python3.6 了,在3.6中提供了loc和iloc兩種索引方法,把ix這個(gè)方法給劃分開來(lái)了,所以很有必要做個(gè)總結(jié)和對(duì)比。
同理,索引列數(shù)據(jù)也是如此!
舉例說(shuō)明:
1、分別使用loc、iloc、ix 索引第一行的數(shù)據(jù):
(1)loc
import pandas as pddata=[[1,2,3],[4,5,6]]index=['a','b']#行號(hào)columns=['c','d','e']#列號(hào)df=pd.DataFrame(data,index=index,columns=columns)#生成一個(gè)數(shù)據(jù)框#print df.loc['a']'''c 1d 2e 3'''print df.loc[0]#這個(gè)就會(huì)出現(xiàn)錯(cuò)誤'''TypeError: cannot do label indexing on <class 'pandas.indexes.base.Index'> with these indexers [1] of <type 'int'>'''
(2)iloc
import pandas as pddata=[[1,2,3],[4,5,6]]index=['a','b']#行號(hào)columns=['c','d','e']#列號(hào)df=pd.DataFrame(data,index=index,columns=columns)#生成一個(gè)數(shù)據(jù)框print df.iloc[0]'''c 1d 2e 3'''print df.iloc['a']'''TypeError: cannot do positional indexing on <class 'pandas.indexes.base.Index'> with these indexers [a] of <type 'str'>'''
(3)ix
import pandas as pddata=[[1,2,3],[4,5,6]]index=['a','b']#行號(hào)columns=['c','d','e']#列號(hào)df=pd.DataFrame(data,index=index,columns=columns)#生成一個(gè)數(shù)據(jù)框print df.ix[0]'''c 1d 2e 3'''print df.ix['a']'''c 1d 2e 3'''
2、分別使用loc、iloc、ix 索引第一列的數(shù)據(jù):
import pandas as pddata=[[1,2,3],[4,5,6]]index=['a','b']#行號(hào)columns=['c','d','e']#列號(hào)df=pd.DataFrame(data,index=index,columns=columns)#生成一個(gè)數(shù)據(jù)框print df.loc[:,['c']]print df.iloc[:,[0]]print df.ix[:,['c']]print df.ix[:,[0]]#結(jié)果都為''' ca 1b 4'''
3、分別使用loc、iloc、ix 索引多行的數(shù)據(jù):
import pandas as pddata=[[1,2,3],[4,5,6]]index=['a','b']#行號(hào)columns=['c','d','e']#列號(hào)df=pd.DataFrame(data,index=index,columns=columns)#生成一個(gè)數(shù)據(jù)框print df.loc['a':'b']print df.iloc[0:1]print df.ix['a':'b']print df.ix[0:1]#結(jié)果都為''' c d ea 1 2 3b 4 5 6'''
4、分別使用loc、iloc、ix 索引多列的數(shù)據(jù):
import pandas as pddata=[[1,2,3],[4,5,6]]index=['a','b']#行號(hào)columns=['c','d','e']#列號(hào)df=pd.DataFrame(data,index=index,columns=columns)#生成一個(gè)數(shù)據(jù)框print df.loc[:,'c':'d']print df.iloc[:,0:2]print df.ix[:,'c':'d']print df.ix[:,0:2]#結(jié)果都為''' c da 1 2b 4 5'''
5、loc、iloc、ix使用切片的區(qū)別
新聞熱點(diǎn)
疑難解答
圖片精選