Pandas中ix,loc,iloc有什么区别?

来源:互联网 发布:nosql和sql有什么不同 编辑:程序博客网 时间:2024/06/05 05:07

直接看例子:

>>> data = pd.Series(np.arange(10), index=[49,48,47,46,45, 1, 2, 3, 4, 5])>>> data49    048    147    246    345    41     52     63     74     85     9dtype: int64>>> data.iloc[:3]49    048    147    2dtype: int64>>> data.loc[:3]49    048    147    246    345    41     52     63     7dtype: int64>>> data.ix[:3]49    048    147    246    345    41     52     63     7dtype: int64
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39

解析: 
loc 在index的标签上进行索引,范围包括start和end. 
iloc 在index的位置上进行索引,不包括end. 
ix 先在index的标签上索引,索引不到就在index的位置上索引(如果index非全整数),不包括end.

>>> data.iloc[:6]49    048    147    246    345    41     5dtype: int64>>> data.loc[:6]KeyError: 6>>> data.ix[:6] #因为index里面不包含标签6,index都是整数KeyError: 6>>> data= pd.Series(np.arange(10), index=['a','b','c','d','e', 1, 2, 3, 4, 5])>>> dataa    0b    1c    2d    3e    41    52    63    74    85    9dtype: int64>>> data.ix[:6]a    0b    1c    2d    3e    41    5dtype: int64>>> data.loc[:6]TypeError: cannot do slice indexing
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

建议: 为了避免歧义,建议优先选择loc和iloc


0 0
原创粉丝点击