网络编程
位置:首页>> 网络编程>> Python编程>> 一文秒懂pandas中iloc()函数

一文秒懂pandas中iloc()函数

作者:方如一  发布时间:2023-07-31 18:20:42 

标签: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
abcd
01234
1100200300400
21000200030004000
'''

一文秒懂pandas中iloc()函数

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]]
abcd
01234
type(df.iloc[[0]])
pandas.core.frame.DataFrame
df.iloc[[0,2]]#取第0、2行
  a   b   c   d
0   1   2   3   4
21000200030004000
df.iloc[0:2,0:3]#取0到1行和0到2列
 a  b   c
0  1  2  3
1100200300
df.iloc[[True, False, True]]#不常用
  a   b   c   d
0   1   2   3   4
21000200030004000
df.iloc[lambda x: x.index % 2 == 0]#函数生成索引列表,x即df
      a   b   c   d
0   1   2   3   4
21000200030004000

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)小明30287
1(行索引1)小王30395
2(行索引2)小方303100

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]

来源:https://blog.csdn.net/Fwuyi/article/details/123127754

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com