Here’s the tutorial of how to sort series in Pandas.
This is the code which contains my series I’d like to sort.
import pandas as pd import numpy as np my_series = pd.Series((3,5,2,6,np.nan,1,7,4)) print(f"This is my series: \n{my_series}")
How to sort series in ascending order
import pandas as pd import numpy as np my_series = pd.Series((3,5,2,6,np.nan,1,7,4)) print(f"This is my series sorted in ascending order: \n{my_series.sort_values()}")
How to sort series in descending order
import pandas as pd import numpy as np my_series = pd.Series((3,5,2,6,np.nan,1,7,4)) print(f"This is my series sorted in descending order: \n{my_series.sort_values(ascending=False)}")
The default value for the ascending parameter is True, so when sorting in descending order you need to use it and change the default value to False.
How to sort NaN values
import pandas as pd import numpy as np my_series = pd.Series((3,5,2,6,np.nan,1,7,4)) print(f"This is my series having NaN values sorted: \n{my_series.sort_values(na_position='first')}")
The default value of the na_position parameter is ‘last’.
Sort_Values function documentation can be found here.
How to sort series in reverse order
import pandas as pd import numpy as np my_series = pd.Series((3,5,2,6,np.nan,1,7,4)) print(f"This is my series sorted in reverse order: \n{my_series.sort_index(ascending=False)}")
Sort_Index function documentation can be found here.
See also:
1 thought on “How to Sort Series”