Multi-Index - Not able to sort multiple indexes in a single line

Viewed 56

I am trying to sort multiple indexes in Python using following code which gives me the error as provided below the code:

raw_data.sort_index(level='employee_id',ascending=False,inplace=True).sort_index(level='PAYCODE_ID',ascending=True,inplace=True)

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-732-d2ad9fdef0b4> in <module>
----> 1 raw_data.sort_index(level='employee_id',ascending=False,inplace=True).sort_index(level='PAYCODE_ID',ascending=True,inplace=True)

AttributeError: 'NoneType' object has no attribute 'sort_index'

I think the python results into 'None' object type after first 'sort_index' method. As per the python documentation, if the 'inplace' parameter is set to True, the return object would be a Data Frame.

Documentation

Also to note that when i split the methods into following two line of code, it stores the sorted result into the raw_data dataframe:

raw_data.sort_index(level='employee_id',ascending=False,inplace=True)
raw_data.sort_index(level='PAYCODE_ID',ascending=True,inplace=True)
1 Answers

If you pass inplace=True to sort_index, the function will operate inplace and returns None. So either remove inplace=True and assign back if you want to chain the commands, or do the two separate commands like you posted.

Also, you can pass multiple levels to sort_index

raw_data.sort_index(level=['employee_id', 'PAYCODE_ID'],
                    ascending=[False, True],inplace=True)
Related