In-place sort_values in pandas what does it exactly mean?

Karel Macek picture Karel Macek · Jan 21, 2017 · Viewed 17k times · Source

Maybe a very naive question, but I am stuck in this: pandas.Series has a method sort_values and there is an option to do it "in place" or not. I have Googled for it a while, but I am not very clear about it. It seems that this thing is assumed to be perfectly known to everybody but me. Could anyone give me some illustrative explanation how these two options differ each other for dummies...?

Thank you for any assistance.

Answer

Alexey Smirnov picture Alexey Smirnov · Jan 21, 2017

Here an example. df1 will hold sorted dataframe and df will be intact

import pandas as pd
from datetime import datetime as dt
df = pd.DataFrame(data=[22,22,3],
                  index=[dt(2016, 11, 10, 0), dt(2016, 11, 10, 13), dt(2016, 11, 13, 5)],
                  columns=['foo'])

df1 = df.sort_values(by='foo')
print(df, df1)

In the case below, df will hold sorted values

import pandas as pd
from datetime import datetime as dt

df = pd.DataFrame(data=[22,22,3],
                  index=[dt(2016, 11, 10, 0), dt(2016, 11, 10, 13), dt(2016, 11, 13, 5)],
                  columns=['foo'])

df.sort_values(by='foo', inplace=True)
print(df)