pandas中的索引:loc、iloc、ix的區別

1、loc:

        1)、只能通過標籤名來取數據
import pandas as pd
lst = [[11,12,13],[14,15,16]]
index = ['row_0','row_1']
columns=['col_0','col_1','col_2']
df = pd.DataFrame(data=lst, index=index, columns=columns)
print df.loc['row_0']

結果:
col_0    11
col_1    12
col_2    13
         2)、不能通過索引(第0行,第1行等)來取數據
import pandas as pd
lst = [[11,12,13],[14,15,16]]
index = ['row_0','row_1']
columns=['col_0','col_1','col_2']
df = pd.DataFrame(data=lst, index=index, columns=columns)
print df.loc[0]

結果:
TypeError: cannot do label indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [0] of <type 'int'>
         3)、取列數據也一樣,要通過標籤名
import pandas as pd
lst = [[11,12,13],[14,15,16]]
index = ['row_0','row_1']
columns=['col_0','col_1','col_2']
df = pd.DataFrame(data=lst, index=index, columns=columns)
print df.loc['row_0',:'col_1']  #等價於df.loc['row_0',['col_0', 'col_1']] 

結果:
col_0    11
col_1    12

2、iloc:

        1)、只能通過索引(第0行,第1行等)來取數據
import pandas as pd
lst = [[11,12,13],[14,15,16]]
index = ['row_0','row_1']
columns=['col_0','col_1','col_2']
df = pd.DataFrame(data=lst, index=index, columns=columns)
print df.iloc[0]

結果:
col_0    11
col_1    12
col_2    13
        2)、使用標籤名則發生錯誤
import pandas as pd
lst = [[11,12,13],[14,15,16]]
index = ['row_0','row_1']
columns=['col_0','col_1','col_2']
df = pd.DataFrame(data=lst, index=index, columns=columns)
print df.iloc['row_0']

結果:
TypeError: cannot do positional indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [row_0] of <type 'str'>
         取列數據就不說了。

3、ix:

       1)、既可以通過標籤名又可以通過索引來取數據
import pandas as pd
lst = [[11,12,13],[14,15,16]]
index = ['row_0','row_1']
columns=['col_0','col_1','col_2']
df = pd.DataFrame(data=lst, index=index, columns=columns)
print df.ix['row_0']
print df.ix[0]

結果都是:
col_0    11
col_1    12
col_2    13
         2)、注意事項:ix優先匹配的是標籤名。例如下面的例子,你可能想通過索引獲取第1行(即[14,15,16]),但恰好行標籤名取的也是整型而不是字符類型,這時返回的就會是第0行(即[11,12,13]),也就是標籤名爲1的那一行。所以爲了避免出錯,儘量不用ix,而是用loc函數和標籤名、用iloc函數和索引來獲取數據!
import pandas as pd
lst = [[11,12,13],[14,15,16]]
index = [1,2]
columns=['col_0','col_1','col_2']
df = pd.DataFrame(data=lst, index=index, columns=columns)
print df.ix[1]

結果:
col_0    11
col_1    12
col_2    13








發佈了37 篇原創文章 · 獲贊 88 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章