【问题标题】:Pandas iloc returns different range than loc [duplicate]熊猫 iloc 返回与 loc 不同的范围 [重复]
【发布时间】:2019-01-19 22:09:55
【问题描述】:

我对 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

我想用 print(template.loc[1:2]) 选择第 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

有人可以解释一下吗?

【问题讨论】:

  • iloc 用于基于整数的索引,不包括 end。 loc 用于基于标签的索引,并包含 end。
  • 查看docs的第三个要点

标签: python pandas dataframe


【解决方案1】:

正如docs 中提到的loc

警告:请注意,与通常的 python 切片相反,开始和 包括站点

另一方面,iloc 会根据基于整数位置的索引进行选择,因此它不包括停止索引。

【讨论】:

  • 谢谢你的回答,@krishna。我想我在文档中错过了这个特性。
猜你喜欢
  • 2021-12-06
  • 2020-07-09
  • 2016-09-10
  • 1970-01-01
  • 2015-10-14
  • 2018-02-09
相关资源
最近更新 更多