Pandas_iloc_loc_哪个是inclusive哪个是exclusive

iloc 和 loc 包括不包括结尾写的那个行(列)?
不一样!
iloc[istart:iend] exclusive on iend 不包括结尾那行(列)!
loc[start:end] inclusive on end
包括结尾那行(列)!

若只选择一行,它俩使用起来完全一样,都是显示该 index 值的那行。

import pandas as pd
df = pd.DataFrame({'x': [1, 2, 3, 4, 2, 6, 8, 4], 
                  'y': [2, 3, 5, 7, 4, 7, 3, 4], 
                  'z': [0, 1, 1, 0, 2, 7, 9, 4]})
df

Output:

	x	y	z
0	1	2	0
1	2	3	1
2	3	5	1
3	4	7	0
4	2	4	2
5	6	7	7
6	8	3	9
7	4	4	4

选择好几行

iloc

df.iloc[:5, :]

Output:
是前5行,index=0 到 index=4 的行,不包括 index=5 那行
一共选择了5行!


	x	y	z
0	1	2	0
1	2	3	1
2	3	5	1
3	4	7	0
4	2	4	2

loc

df.loc[:5, :]

Output:
居然是前6行,是 index=0 到 index=5 的行,包括 index=5 那行
一共选择了6行!
记住:loc写什么,就显示到什么地方


	x	y	z
0	1	2	0
1	2	3	1
2	3	5	1
3	4	7	0
4	2	4	2
5	6	7	7

1 2
iloc[istart:iend] exclusive on iend 不包括结尾那行(列)!
loc[start:end] inclusive on end
包括结尾那行(列)!

如果选择列呢?

iloc

df.iloc[:, :2]

Output:
还是前两列,index=0 到 index=1


	x	y
0	1	2
1	2	3
2	3	5
3	4	7
4	2	4
5	6	7
6	8	3
7	4	4

loc

# df.loc[:, :2] # 没这么写的,报错
df.loc[:, df.columns[:2]]

Output:
还是前两列,index=0 到 index=1 注意哦,因为用的是df.columns[]


	x	y
0	1	2
1	2	3
2	3	5
3	4	7
4	2	4
5	6	7
6	8	3
7	4	4

只选择一行

它俩使用起来完全一样。

iloc

df.iloc[5, :]

Output:

x    6
y    7
z    7
Name: 5, dtype: int64

loc

df.loc[5, :]

Output:

x    6
y    7
z    7
Name: 5, dtype: int64
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

「已注销」

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值