Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For a pandas Series, shouldn't s.sort_index(inplace=True) change s?

Tags:

python

pandas

Given this code:

s = pd.Series([1,2,3], index=['C','B','A'])
s.sort_index(inplace=True)

Shouldn't s now look like this:

A    3
B    2
C    1
dtype: int64

When I run this, s remains unchanged. Maybe I'm confused about what the inplace argument is supposed to do. I thought that it was supposed to change the Series on which the method is called.

For the record, this does return the sorted series, but it does so whether or not you set inplace to True.

like image 888
Webucator Avatar asked Dec 19 '22 22:12

Webucator


2 Answers

You are indeed correct with your expectation. However, this was not yet implemented before 0.17 / a bug in 0.17 that this keyword was ignored instead of raising an error (like before). But a fix will be released in the upcoming version 0.17.1.

See https://github.com/pydata/pandas/pull/11422

So for now, easiest is just to use it without inplace:

In [4]: s = s.sort_index()

In [5]: s
Out[5]:
A    3
B    2
C    1
dtype: int64
like image 115
joris Avatar answered Feb 15 '23 22:02

joris


You need to have a dataframe:

s = pd.DataFrame([1,2,3], index=['C','B','A'])

s.sort_index(inplace=True)

s
Out[25]: 
   0
A  3
B  2
C  1

inplace for sort_index works on DataFrame, not series. For series you have to redefine it.

like image 44
Leb Avatar answered Feb 16 '23 00:02

Leb