Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas mix position and label indexing without chaining

Tags:

slice

pandas

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.

like image 815
Zhang18 Avatar asked Jun 26 '17 16:06

Zhang18


People also ask

Which method is used for label location indexing by label?

loc attribute is the primary access method. The following are valid inputs: A single label, e.g. 5 or 'a', (note that 5 is interpreted as a label of the index. This use is not an integer position along the index)

Can I use ILOC and loc together?

loc and iloc are interchangeable when labels are 0-based integers.

Can a DataFrame have multiple indexes?

A multi-level index DataFrame is a type of DataFrame that contains multiple level or hierarchical indexing. You can create a MultiIndex (multi-level index) in the following ways.


2 Answers

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
like image 191
Scott Boston Avatar answered Jan 22 '23 06:01

Scott Boston


maybe I should've explained clearer. I meant if your dataframe is indexed (with 0 to n), then you can use loc[] for a combination of number for rows and lable for column:

new_df = pd.DataFrame({'a':[1,2,3,4],'b':[5,6,7,8]})
new_df
Out[10]:
   a  b
0  1  5
1  2  6
2  3  7
3  4  8

new_df.loc[0,'a']
Out[11]:
1
like image 33
Mohammad Amin Takroosta Avatar answered Jan 22 '23 06:01

Mohammad Amin Takroosta