0
点赞
收藏
分享

微信扫一扫

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

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

一、loc函数

构建数据集df

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']是可以的。

n[13]: df.loc[:,0:1]
Out[13]:
0 1
0 green M
1 red L
2 blue XL

二、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型。

三、ix函数

ix——结合前两种的混合索引,即可以是行序号,也可以是行标签。

另,一些筛选操作

如选择prize>10(prize为一个标签)的,即 df.loc[df.prize>10]
还有&并或等操作

参考文献:

python选取特定列——pandas的iloc和loc以及icol使用

pandas入门——loc与iloc函数

pandas中loc、iloc、ix的区别

pandas基础之按行取数(DataFrame)

举报

相关推荐

0 条评论