python .loc vs .iloc區別

  1.loc意義:經過行標籤索引行數據

       例: loc[n]表示索引的是第n行(index 是整數)spa

              loc[‘d’]表示索引的是第’d’行(index 是字符)索引

   2. .iloc   :經過行號獲取行數據,不能是字符pandas

   3.  ix——結合前兩種的混合索引io

三者區別: import

ix / loc 能夠經過行號和行標籤進行索引,好比 df.loc['a'] , df.loc[1], df.ix['a'] , df.ix[1]sed

而iloc只能經過行號索引 , df.iloc[0] 是對的, 而df.iloc['a'] 是錯誤的numpy

建議:im

當用行號索引的時候, 儘可能用 iloc 來進行索引; 而用標籤索引的時候用 loc ,  ix 儘可能別用。數據

例:stl

     import numpy as np

   import pandas as pd

df=pd.DataFrame(np.arange(0,60,2).reshape(10,3),columns=list('abc'))
print(df)

     a    b    c
 0  0   2    4
1   6   8  10
2 12 14 16
3 18 20 22
4 24 26 28
5 30 32 34
6 36 38 40
7 42 44 46
8 48 50 52
9 54 56 58


print df.iloc[0] #輸出第0行全部列內容

a 0
b 2
c 4
Name: 0, dtype: int32

 print df.iloc[0:3] #輸出0至3行全部列內容

      a     b    c

0  0     2    4
1  6     8  10
2 12 14 16

print df.iloc[1,2] #輸出第一行第二列

   10

 print df.iloc[1,‘c’]  #輸出第一行第二列,由於用了標籤索引,因此會報錯

ValueError: Location based indexing can only have [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array] types

print df.loc[0,'a']

 0

print df.loc[0:3,['a','b']]

      a   b
0    0  2
1   6   8
2 12 14
3 18 20

print df.loc[[1,5],['b','c']]

     b  c
1  8 10
5 32 34

爲便於區分,全部屏幕輸出結果,所有用斜體

相關文章
相關標籤/搜索