pandas mix position and label indexing without chaining

久未见 提交于 2019-12-07 02:47:03

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/44764042/pandas-mix-position-and-label-indexing-without-chaining

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!