python - Pandas iloc 返回的范围与 loc 不同
问题描述
我对 pandas 的 iloc 函数有点困惑,因为我想选择一个列范围并且输出与预期不同。行选择也会发生同样的情况,所以我写了一个小例子:
template = pd.DataFrame(
{'Headline': ['Subheading', '', 'Animal', 'Tiger', 'Bird', 'Lion'],
'Headline2': ['', 'Weight', 2017, 'group1', 'group2', 'group3'],
'Headline3': ['', '', 2018, 'group1', 'group2', 'group3']
})
Headline Headline2 Headline3
0 Subheading
1 Weight
2 Animal 2017 2018
3 Tiger group1 group1
4 Bird group2 group2
5 Lion group3 group3
我想选择第 1 行到第 2 行,print(template.loc[1:2])
结果是我所期望的:
Headline Headline2 Headline3
1 Weight
2 Animal 2017 2018
如果我这样做,print(template.iloc[1:2])
我会认为我会得到相同的结果,但不是:
Headline Headline2 Headline3
1 Weight
我有点困惑,因为我希望这两个函数的行为相同,但是如果我选择一个范围(FROM:TO),两个函数的输出会有所不同。
似乎使用 iloc 需要 TO 值 +1 才能获得与 loc 相同的结果print(template.iloc[1:3])
:
Headline Headline2 Headline3
1 Weight
2 Animal 2017 2018
有人可以点亮它吗?
解决方案
推荐阅读
- python - Celery link_error 引发 NotRegistered 异常
- asp.net-core - 如何从 Identity Server 4 端点获取路由数据
- apache-spark - 检索列中具有不同值的 Spark 数据集
- python - 在嵌套的 for 循环中使用 try-excepts
- google-cloud-platform - 导入到 SQL Mysql 实例
- c# - 我的子弹在第一次射击后不会移动,为什么?
- python - python -m 在公司代理后面
- .net - VB、.Net 非阻塞 TcpClient
- javascript - 使用 React 组件自定义 Bootstrap SCSS
- c# - 搜索空白字段时出现字符串比较错误