Python | iloc和loc的区别

import pandas as pd
  • 获取列 首先在pandas中我们想要获取一列,很简单,df[‘A’]

  • 获取行 有loc和iloc的方法

  • loc:works on labels in the index.(索引+列名)

  • iloc:works on the positions in the index (so it only takes integers).(行号 从0开始)

1 生成DataFrame

df = pd.DataFrame(np.arange(0,60,2).reshape(10,3),columns=list('abc'))
# np.arange(0,60,2) 表示以2为步长从0走到60 按行来!
df
abc
0024
16810
2121416
3182022
4242628
5303234
6363840
7424446
8485052
9545658

2 取第a列

2.1 方法1
df.loc[:, 'a'] # 取第a列
0     0
1     6
2    12
3    18
4    24
5    30
6    36
7    42
8    48
9    54
Name: a, dtype: int64
2.2 方法2
df['a']
0     0
1     6
2    12
3    18
4    24
5    30
6    36
7    42
8    48
9    54
Name: a, dtype: int64
2.3 方法3
df.iloc[:, 0]
0     0
1     6
2    12
3    18
4    24
5    30
6    36
7    42
8    48
9    54
Name: a, dtype: int64

3 取倒数第一行的值

3.1 法1
df.iloc[-1] # 取倒数第一行的值
a    54
b    56
c    58
Name: 9, dtype: int64
df.iloc[2]
a    12
b    14
c    16
Name: 2, dtype: int64
df.iloc[-1,:] # 也可以直接用-1即可
a    54
b    56
c    58
Name: 9, dtype: int64
3.2 方法2
df.loc[df.index.max()]
a    54
b    56
c    58
Name: 9, dtype: int64
df.loc[df.index.max(), :]
a    54
b    56
c    58
Name: 9, dtype: int64

4 取第1行到第3行

df.iloc[1:4]
abc
16810
2121416
3182022

5 取第2行第3列的值

5.1 方法1
df.loc[1, 'c']
10
5.2 方法2
df.iloc[1, 2]
10

6 总结

  • 无论是iloc还是loc 均采用[]而不是括号
  • 如果只是取行 建议用iloc 因为比较简单
  • 如果列和行同时取 建议采用loc 因为可以直接定义到标签
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值