pandas mix position and label indexing without cha

2019-05-03 07:13发布

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'>

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.

标签: pandas slice
1条回答
迷人小祖宗
2楼-- · 2019-05-03 08:09

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
查看更多
登录 后发表回答