首页 > 解决方案 > 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

有人可以点亮它吗?

标签: pythonpandasdataframe

解决方案


正如它在文档中提到的loc

警告:请注意,与通常的 python 切片相反,开始和停止都包括在内

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


推荐阅读