How to sort a column alphabetically in Pandas

You can sort a column alphabetically in Pandas with the following code. I highly recommend you This book to learn Python.

Step 1: Install Pandas Library

Install the Pandas library using this code, if it is not installed.

pip install pandas

Example 1: Sort a column alphabetically in Ascending Order

# Import the Pandas library as pd
import pandas as pd

# Initialize a dictionary
dict = {'Name':['Hussain', 'John', 'Ali', 'Satish'],
        'Marks':[75, 80, 85, 82]}

# Create DataFrame from dictionary
df = pd.DataFrame(dict)

# Display the DataFrame
print(df)

# Sorting in Ascending Order
df.sort_values(by=['Name'], inplace=True)

# Display the DataFrame
print(df)

Output:

      Name  Marks
0  Hussain     75
1     John     80
2      Ali     85
3   Satish     82
      Name  Marks
2      Ali     85
0  Hussain     75
1     John     80
3   Satish     82

Example 2: Sort a column alphabetically in Descending Order

# Import the Pandas library as pd
import pandas as pd

# Initialize a dictionary
dict = {'Name':['Hussain', 'John', 'Ali', 'Satish'],
        'Marks':[75, 80, 85, 82]}

# Create DataFrame from dictionary
df = pd.DataFrame(dict)

# Display the DataFrame
print(df)

# Sorting in Descending Order
df.sort_values(by=['Name'], inplace=True, ascending=False)

# Display the DataFrame
print(df)

Output:

      Name  Marks
0  Hussain     75
1     John     80
2      Ali     85
3   Satish     82
      Name  Marks
3   Satish     82
1     John     80
0  Hussain     75
2      Ali     85

Free Learning Resources

Leave a Comment

Your email address will not be published.