一文秒懂pandas中iloc()函数
pandas中iloc()函数
DataFrame.iloc
纯基于整数位置的索引。
import pandas as pd mydict = [{'a': 1, 'b': 2, 'c': 3, 'd': 4}, {'a': 100, 'b': 200, 'c': 300, 'd': 400}, {'a': 1000, 'b': 2000, 'c': 3000, 'd': 4000 }] '''mydict [{'a': 1, 'b': 2, 'c': 3, 'd': 4}, {'a': 100, 'b': 200, 'c': 300, 'd': 400}, {'a': 1000, 'b': 2000, 'c': 3000, 'd': 4000}]''' df = pd.DataFrame(mydict) ''' df a b c d 0 1 2 3 4 1 100 200 300 400 2 1000 2000 3000 4000 '''
df.iloc[0]#取第0行 a 1 b 2 c 3 d 4 Name: 0, dtype: int64 df.iloc[0].shape (4,) type(df.iloc[0].shape) tuple df.iloc[[0]] a b c d 0 1 2 3 4 type(df.iloc[[0]]) pandas.core.frame.DataFrame df.iloc[[0,2]]#取第0、2行 a b c d 0 1 2 3 4 2 1000 2000 3000 4000 df.iloc[0:2,0:3]#取0到1行和0到2列 a b c 0 1 2 3 1 100 200 300 df.iloc[[True, False, True]]#不常用 a b c d 0 1 2 3 4 2 1000 2000 3000 4000 df.iloc[lambda x: x.index % 2 == 0]#函数生成索引列表,x即df a b c d 0 1 2 3 4 2 1000 2000 3000 4000
Pandas库中iloc[ ]函数使用详解
1 iloc[]函数作用
iloc[]函数,属于pandas库,全称为index location,即对数据进行位置索引,从而在数据表中提取出相应的数据。
2 iloc函数使用
df.iloc[a,b],其中df是DataFrame数据结构的数据(表1就是df),a是行索引(见表1),b是列索引(见表1)。
姓名(列索引10) | 班级(列索引1) | 分数(列索引2) | |
0(行索引0) | 小明 | 302 | 87 |
1(行索引1) | 小王 | 303 | 95 |
2(行索引2) | 小方 | 303 | 100 |
1.iloc[a,b]:取行索引为a列索引为b的数据。
import pandas df = pandas.read_csv('a.csv') print(df.iloc[1,2]) #Out:95
2.iloc[a:b,c]:取行索引从a到b-1,列索引为c的数据。注意:在iloc中a:b是左到右不到的,即lioc[1:3,:]是从行索引从1到2,所有列索引的数据。
import pandas df = pandas.read_csv('a.csv') print(df.iloc[0:2,2]) #数据结构是Series print(df.iloc[0:2,2].values) #数据结构是ndarray #Out1:0 87 # 1 95 # Name: 分数, dtype: int64 #Out2:[87 95]
iloc[].values,用values属性取值,返回ndarray,但是单个数值无法用values函数读取。
3.iloc[a:b,c:d]:取行索引从a到b-1,列索引从c到d-1的数据。
import pandas df = pandas.read_csv('a.csv') print(df.iloc[0:2,0:2]) print(df.iloc[0:2,0:2].values) #Out1: 姓名 班级 # 0 小明 302 # 1 小王 303 #Out2:[['小明' 302] # ['小王' 303]]
4.iloc[a]:取取行索引为a,所有列索引的数据。
import pandas df = pandas.read_csv('a.csv') print(df.iloc[2]) print(df.iloc[2].values) #Out1:姓名 小方 # 班级 303 # 分数 100 # Name: 2, dtype: object #Out2:['小方' 303 100]
到此这篇关于Pandas库中iloc[ ]函数使用详解的文章就介绍到这了,更多相关Pandas iloc[ ]函数内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
python numpy和list查询其中某个数的个数及定位方法
今天小编就为大家分享一篇python numpy和list查询其中某个数的个数及定位方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2018-06-06
最新评论