In-place sort_values in pandas what does it exactly mean?
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)
As you can read from the sort_values document, the return value of the function is a series. However, it is a new series instead of the original.
For example:
import numpy as np
import pandas as pd
s = pd.Series(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e'])
print(s)
a -0.872271
b 0.294317
c -0.017433
d -1.375316
e 0.993197
dtype: float64
s_sorted = s.sort_values()
print(s_sorted)
d -1.375316
a -0.872271
c -0.017433
b 0.294317
e 0.993197
dtype: float64
print(id(s_sorted))
127952880
print(id(s))
127724792
So s
and s_sorted
are different series.
But if you use inplace=True.
s.sort_values(inplace=True)
print(s)
d -1.375316
a -0.872271
c -0.017433
b 0.294317
e 0.993197
dtype: float64
print(id(s))
127724792
It shows they are the same series, and no new series will return.