參考了幾個部落格,做了以下整理,如有雷同,是我抄别人的。。
參考連結:https://blog.csdn.net/xw_classmate/article/details/51333646
https://blog.csdn.net/hecongqing/article/details/61927615
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
'''
1.3 如果想索引列資料,像這樣做會報錯
import pandas as pd
data = [[1,2,3],[4,5,6]]
index = ['d','e']
columns=['a','b','c']
df = pd.DataFrame(data=data, index=index, columns=columns)
print df.loc['a']
'''
KeyError: 'the label [a] is not in the [index]'
'''
1.4 loc可以擷取多行資料
import pandas as pd
data = [[1,2,3],[4,5,6]]
index = ['d','e']
columns=['a','b','c']
df = pd.DataFrame(data=data, index=index, columns=columns)
print df.loc['d':]
'''
a b c
d 1 2 3
e 4 5 6
'''
1.5 loc擴充——索引某行某列
import pandas as pd
data = [[1,2,3],[4,5,6]]
index = ['d','e']
columns=['a','b','c']
df = pd.DataFrame(data=data, index=index, columns=columns)
print df.loc['d',['b','c']]
'''
b 2
c 3
'''
1,6 loc擴充——索引某列
import pandas as pd
data = [[1,2,3],[4,5,6]]
index = ['d','e']
columns=['a','b','c']
df = pd.DataFrame(data=data, index=index, columns=columns)
print df.loc[:,['c']]
'''
c
d 3
e 6
'''
當然擷取某列資料最直接的方式是df.[列标簽],但是當列标簽未知時可以通過這種方式擷取列資料。
需要注意的是,dataframe的索引[1:3]是包含1,2,3的,與平時的不同。