• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

为什么.loc具有片的包容性行为?

用户头像
it1352
帮助1

问题说明

由于某些原因,以下两个对iloc/loc的调用会产生不同的行为:

For some reason, the following 2 calls to iloc / loc produce different behavior:

>>> import pandas as pd
>>> df = pd.DataFrame(dict(A=range(3), B=range(3)))
>>> df.iloc[:1]
   A  B
0  0  0
>>> df.loc[:1]
   A  B
0  0  0
1  1  1

我知道loc考虑行标签,而iloc考虑行的基于整数的索引.但是为什么loc调用的上限被认为是包含的,而iloc调用的上限却被认为是排他的呢?

I understand that loc considers the row labels, while iloc considers the integer-based indices of the rows. But why is the upper bound for the loc call considered inclusive, while the iloc bound is considered exclusive?

正确答案

#1

快速解答:

使用标签时,进行端到端切片通常更有意义,因为它需要有关DataFrame中其他行的知识较少.

It often makes more sense to do end-inclusive slicing when using labels, because it requires less knowledge about other rows in the DataFrame.

每当您关心标签而不是位置时,末端排他的标签切片都会以一种不方便的方式引入位置依赖性.

Whenever you care about labels instead of positions, end-exclusive label slicing introduces position-dependence in a way that can be inconvenient.

更长的答案:

任何函数的行为都是一个权衡:您偏爱某些用例而不是其他用例.最终,.iloc的操作是熊猫开发人员的主观设计决定(正如@ALlollz的评论所指出的,此行为 @Willz的答案:

That said, maybe there are use cases where you really do want end-exclusive label-based slicing. If so, you can use @Willz's answer in this question:

df.loc[start:end].iloc[:-1]

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfgihc
系列文章
更多 icon
同类精品
更多 icon
继续加载