Python 基本操作- 数据选取loc、iloc、ix函数

loc中的数据是列名,是字符串,所以前后都要取;iloc中数据是int整型,所以是Python默认的前闭后开
一:LOC函数

import pandas as pd  
df = pd.DataFrame([  
            ['green', 'M', 10.1, 'class1'],   
            ['red', 'L', 13.5, 'class2'],   
            ['blue', 'XL', 15.3, 'class1']])  
print (df)    
# 数据集为以下内容,所有操作均对df进行
       0   1     2       3
0  green   M  10.1  class1
1    red   L  13.5  class2
2   blue  XL  15.3  class1

LOC函数主要通过行标签索引数据,划重点标签
loc[1] 选择行标签是1的(从0、1、2、3这几个行标签中)
**In[1]: df.loc[1]
Out[1]:
0 red
1 L
2 13.5
3 class2
**
loc[0:1] 和 loc[0,1]的区别,其实最重要的是loc[0:1]和iloc[0:1]

In[10]: df.loc[0:1]  #取第一和第二行,loc[]中的数字其实是行索引,所以算是前闭加后闭
Out[10]: 
       0  1     2       3
0  green  M  10.1  class1
1    red  L  13.5  class2

In[12]:   df.iloc[0:1]
Out[12]: 
       0  1     2       3
0  green  M  10.1  class1

In[11]:   df.loc[0,1]
Out[11]: 'M'

索引某一列数据,loc[:,0:1],还是标签,注意,如果列标签是个字符,比如’a’,loc[‘a’]是不行的,必须为loc[:,‘a’]。
但如果行标签是’a’,选取这一行,用loc[‘a’]是可以的。

二、iloc函数
iloc 主要是通过行号获取行数据,划重点,序号!序号!序号!
iloc[0:1],由于Python默认是前闭后开,所以,这个选择的只有第一行!

In[12]:   df.iloc[0:1]
Out[12]: 
       0  1     2       3
0  green  M  10.1  class1

如果想用标签索引,如iloc[‘a’],就会报错,它只支持int型。

你可能感兴趣的:(Python 基本操作- 数据选取loc、iloc、ix函数)