1.索引分类

1.1类型

索引类型 说明
整数索引 与数组的整数下标相同,从0开始到n-1,通过下标选择数据,可以使用切片的方式选择数据。
标签索引 参数index、columns中指定的名称,直接通过名称选择数据,也可以使用切片的方式选择数据。
布尔索引 这与numpy的索引方式相似,相当于选择满足条件的数据。

1.2 注意

1,若直接使用[ ]选择数据时,不能直接选择具体的元素。
用’column_name’,即列的轴标签选择列的数据。
用’index_sliceable’,即行的整数索引或标签索引的切片选择行数据。

import pandas as pd
import numpy as np

frame = pd.DataFrame(np.arange(25).reshape((5, -1)),
                     index=list('abcde'),
                     columns=['one', 'two', 'three', 'four', 'five'])
print(frame[['one', 'five']])  #用'column_name'

print(frame[:3])   # 用'index_sliceable',index切片

至于为啥会是这样规定,debug了下,没看懂,但是看到这两句代码,有知道原因的可麻烦评论告诉我。

indexer = self.columns.get_loc(key)
indexer = convert_to_index_sliceable(self, key)

2,在切片时,整数索引与标签索引的切片结果有差异

print(frame[:3])    #左闭右开
"""
   one  two  three  four  five
a    0    1      2     3     4
b    5    6      7     8     9
c   10   11     12    13    14
"""
print(frame[:'c'])    #左闭右闭
"""
   one  two  three  four  five
a    0    1      2     3     4
b    5    6      7     8     9
c   10   11     12    13    14
"""

可以看出区别,用整数索引进行切片时,左边等于右边不等于,即是0<= index < 2,而使用标签索引则是’a’<= index<=‘c’。 所以需要注意这两种类型的索引使用。

2.loc和iloc

DataFrame可以使用loc和iloc来选择数据,而两者是根据“标签”或“整数”索引来选择的,

print(frame.loc['a':'c', :'three'])
"""
   one  two  three
a    0    1      2
b    5    6      7
c   10   11     12
"""
print(frame.iloc[0:, :3])
"""
   one  two  three
a    0    1      2
b    5    6      7
c   10   11     12
d   15   16     17
e   20   21     22
"""

3.at和iat

与loc和iloc类似,都提供基于整数或者标签索引的查找。如果只需要获取或设置单个值时,可使用at和iat。

print(frame.at['a', 'three'])   #2
print(frame.iat[0, 3])   #3

frame.iat[0, 0] = 100   # 修改元素
print(frame)

最后,正是由于pandas功能这么强大,整数索引和标签索引,将标签设置为整数时,就会造成歧义。所以,如果使用整数作为标签,那么在数据选择是使用loc 或者 iloc,这样可以明确知道使用的是哪种类型的索引,从而精确地选择数据。

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐