Pandas iloc 返回的范围与 loc 不同

Eri*_*ner 4 python dataframe pandas

我对 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
Run Code Online (Sandbox Code Playgroud)

我想选择第 1 行到第 2 行,print(template.loc[1:2])结果是我所期望的:

  Headline Headline2 Headline3
1             Weight          
2   Animal      2017      2018
Run Code Online (Sandbox Code Playgroud)

如果我这样做,print(template.iloc[1:2])我会认为我会得到相同的结果,但没有:

  Headline Headline2 Headline3
1             Weight          
Run Code Online (Sandbox Code Playgroud)

我有点困惑,因为我期望这两个函数具有相同的行为,但是如果我选择一个范围(FROM:TO),两个函数的输出会有所不同。
似乎使用 iloc 需要将 TO 值 +1 才能获得与 loc 相同的结果print(template.iloc[1:3])

  Headline Headline2 Headline3
1             Weight          
2   Animal      2017      2018
Run Code Online (Sandbox Code Playgroud)

有人可以解释一下吗?

Lev*_*rov 5

正如文档中提到的loc

警告:请注意,与通常的 python 切片相反,开始和结束都包含在内

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