因為這個問題困擾過我,是以在此作為自己學習筆記,标記一下
原文位址:https://www.cnblogs.com/jeasonit/p/9994864.html
loc——通過行标簽索引行資料
iloc——通過行号索引行資料
ix——通過行标簽或者行号索引行資料(基于loc和iloc 的混合)
同理,索引列資料也是如此!
舉例說明:
1、分别使用loc、iloc、ix 索引第一行的資料:
(1)loc
import pandas as pd
data=[[1,2,3],[4,5,6]]
index=['a','b']#行号
columns=['c','d','e']#列号
df=pd.DataFrame(data,index=index,columns=columns)#生成一個資料框
#print df.loc['a']
'''
c 1
d 2
e 3
'''
print df.loc[0]
#這個就會出現錯誤
'''
TypeError: cannot do label indexing on <class 'pandas.indexes.base.Index'>
with these indexers [1] of <type 'int'>
(2)iloc
import pandas as pd
data=[[1,2,3],[4,5,6]]
index=['a','b']#行号
columns=['c','d','e']#列号
df=pd.DataFrame(data,index=index,columns=columns)#生成一個資料框
print df.iloc[0]
'''
c 1
d 2
e 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 pd
data=[[1,2,3],[4,5,6]]
index=['a','b']#行号
columns=['c','d','e']#列号
df=pd.DataFrame(data,index=index,columns=columns)#生成一個資料框
print df.ix[0]
'''
c 1
d 2
e 3
'''
print df.ix['a']
'''
c 1
d 2
e 3
'''
2、分别使用loc、iloc、ix 索引第一列的資料:
import pandas as pd
data=[[1,2,3],[4,5,6]]
index=['a','b']#行号
columns=['c','d','e']#列号
df=pd.DataFrame(data,index=index,columns=columns)#生成一個資料框
print df.loc[:,['c']]
print df.iloc[:,[0]]
print df.ix[:,['c']]
print df.ix[:,[0]]
#結果都為
'''
c
a 1
b 4
3、分别使用loc、iloc、ix 索引多行的資料:
import pandas as pd
data=[[1,2,3],[4,5,6]]
index=['a','b']#行号
columns=['c','d','e']#列号
df=pd.DataFrame(data,index=index,columns=columns)#生成一個資料框
print df.loc['a':'b']
print df.iloc[0:1]
print df.ix['a':'b']
print df.ix[0:1]
#結果都為
'''
c d e
a 1 2 3
b 4 5 6
4、分别使用loc、iloc、ix 索引多列的資料:
import pandas as pd
data=[[1,2,3],[4,5,6]]
index=['a','b']#行号
columns=['c','d','e']#列号
df=pd.DataFrame(data,index=index,columns=columns)#生成一個資料框
print df.loc[:,'c':'d']
print df.iloc[:,0:2]
print df.ix[:,'c':'d']
print df.ix[:,0:2]
#結果都為
'''
c d
a 1 2
b 4 5
'''
——————————————————— 分割線 ———————————————————————
最後,以下是個人的總結,在python 3.7版本中,使用 ix 則給出了如下的警告:
DeprecationWarning:
.ix is deprecated. Please use
.loc for label based indexing or
.iloc for positional indexing
是以,還是嚴格地使用.loc 和 .iloc 吧!