pandas 混合位置和标签索引,无需链接 [英] pandas mix position and label indexing without chaining

查看:70
本文介绍了 pandas 混合位置和标签索引,无需链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从Pandas开始已弃用.ix 0.20 ,我想知道在熊猫中混合基于标签,基于布尔和基于位置的索引的正确方法是什么?我需要将值分配给数据框的一部分,最好在索引和列的位置上使用label或boolean进行引用.例如(使用.loc作为所需切片方法的占位符):

Since .ix has been deprecated as of Pandas 0.20, I wonder what is the proper way to mix lable-based, boolean-based and position-based indexing in Pandas? I need to assign values to a slice of dataframe that can be best referenced with label or boolean on the index and position on the columns. For example (using .loc as placeholder for the desired slicing method):

df.loc[df['a'] == 'x', -12:-1] = 3

显然这不起作用,我得到了:

obviously this doesn't work, with which I get:

TypeError: cannot do slice indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [-12] of <class 'int'>

如果我使用.iloc,我会得到:

If I use .iloc, I get:

NotImplementedError: iLocation based boolean indexing on an integer type is not available

那么,如何在没有链接的情况下做到这一点,显然可以避免链接分配问题.

So how do I do it, without chaining, obviously to avoid chained assignment problem.

推荐答案

让我们将.loc与布尔索引一起使用,并通过具有索引切片的数据框列索引访问列标签:

Let's use .loc with the boolean indexing, and accessing the column labels via the dataframe column index with index slicing:

df.loc[df['a'] == 'x', df.columns[-12:-1]] = 3

这篇关于 pandas 混合位置和标签索引,无需链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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