为什么熊猫按位置索引子集会出现错误?

罗迪克斯

我正在阅读韦斯·麦金尼(Wes Mckinney)撰写的有关熊猫的书,偶然发现了这个例子。

people = DataFrame(np.random.randn(5, 5),
                   columns=['a', 'b', 'c', 'd', 'e'],
                   index=['Joe', 'Steve', 'Wes', 'Jim', 'Travis'])

如果要在适当位置修改数据框,则必须运行以下命令

people.loc[2:3, ['b', 'c']] = np.nan

基于标签索引,并避免使用SettingWithCopyWarning。该命令可以正常运行,并且相应地更改了数据框。
我的问题是,为什么如果我运行下面的代码(与上面的代码相同,但未为子集分配值),却出现索引错误?我知道.loc是标签索引编制,我们不应该使用2:3,但是为什么在分配值时也不会出现错误?

people.loc[2:3, ['b', 'c']]

结果:

TypeError: cannot do slice indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [2] of <class 'int'>
代码不同

这需要改变观念。如果您熟悉Python中的list / ndarray,那么您会知道在执行此分配时:

array[42] = 10

...索引42必须存在,否则您将获得IndexError

熊猫将惯例翻转为“如果没有帮助,则创建它”。因此,当您分配东西时,大熊猫将更改位置或创建一个新的位置:

people['age'] = ...               # create a new column called `age`
people.loc[2:3, ['b', 'c']] = ... # create rows with labels 2 and 3 and assign
                                  # some values for column `b` and `c`

如果这些位置已经存在值,则将对其进行修改。

“ get”操作仍然像以前一样工作:您无法检索不存在的内容:

people['gender']    # KeyError. Column `gender` does not exist
people.loc[5]       # TypeError. Can't find row with label 5 in the index

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章