Wednesday 8 November 2023

In-Place Sorting of DataFrames in Pandas

If you set the argument inplace to True, while calling sort_values method, then the sorting update the original DataFrame.

 

Example

df.sort_values('Age', inplace=True)

 

Find the below working application.

 

sort_in_place.py

import pandas as pd
import numpy as np

# Create a sample DataFrame
data = {'Name': ['Krishna', 'Sailu', 'Joel', 'Chamu', 'Jitendra', "Raj"],
        'Age': [34, 35, 29, np.nan, 52, np.nan],
        'City': ['Bangalore', 'Hyderabad', None, 'Chennai', None, 'Chennai'],
        'Gender': ['Male', 'Female', 'Male', 'Female', 'Male', 'Male']}
df = pd.DataFrame(data)

print('\nSort by Age :')
sort_by_age_ascending = df.sort_values('Age')
print(sort_by_age_ascending)

print('\nOriginal DataFrame')
print(df)

print("Sort by Age in place : ")
df.sort_values('Age', inplace=True)
print('\nOriginal DataFrame')
print(df)

 

Output

Sort by Age :
       Name   Age       City  Gender
2      Joel  29.0       None    Male
0   Krishna  34.0  Bangalore    Male
1     Sailu  35.0  Hyderabad  Female
4  Jitendra  52.0       None    Male
3     Chamu   NaN    Chennai  Female
5       Raj   NaN    Chennai    Male

Original DataFrame
       Name   Age       City  Gender
0   Krishna  34.0  Bangalore    Male
1     Sailu  35.0  Hyderabad  Female
2      Joel  29.0       None    Male
3     Chamu   NaN    Chennai  Female
4  Jitendra  52.0       None    Male
5       Raj   NaN    Chennai    Male
Sort by Age in place : 

Original DataFrame
       Name   Age       City  Gender
2      Joel  29.0       None    Male
0   Krishna  34.0  Bangalore    Male
1     Sailu  35.0  Hyderabad  Female
4  Jitendra  52.0       None    Male
3     Chamu   NaN    Chennai  Female
5       Raj   NaN    Chennai    Male

 

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment