pandas iloc返回的范围与loc不同 [英] Pandas iloc returns different range than loc

查看:174
本文介绍了 pandas iloc返回的范围与loc不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对pandas的iloc函数有些困惑,因为我想选择一系列列,并且输出与预期的不同.行选择也会发生同样的情况,所以我写了一个小例子:

I am a bit confused of the iloc function of pandas, because I want to select a range of columns and the output is different than expected. The same will happen to row selection, so I wrote a little example:

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行,结果是我所期望的:

I want to select line 1 to line 2 with print(template.loc[1:2]) the result is what I have expected:

  Headline Headline2 Headline3
1             Weight          
2   Animal      2017      2018

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

If I do this print(template.iloc[1:2]) I would think that I get the same result, but no:

  Headline Headline2 Headline3
1             Weight          

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

I am a bit confused, because I expected the same behavior for both functions, but the output of both functions differ if I select a range (FROM:TO).
It seems like using iloc needs to have the TO value +1 in order to have the same result as loc print(template.iloc[1:3]):

  Headline Headline2 Headline3
1             Weight          
2   Animal      2017      2018

有人可以给它一些照明吗?

Can someone put some light on it?

推荐答案

As it mentioned in docs for loc:

警告:请注意,与通常的python片相反,开始和终止 停止了

Warning: Note that contrary to usual python slices, both the start and the stop are included

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

On the other hand, iloc do selects based on integer-location based indexing, so it doesn't include stop index.

这篇关于 pandas iloc返回的范围与loc不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆