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