Search⌘ K
AI Features

Solution: Sorting, Columns, Filtering, and Indexing Operations

Explore techniques to sort DataFrame indexes and columns in ascending or descending order. Learn how to filter and select specific rows and columns using label-based and position-based indexing in pandas. This lesson equips you with practical skills for organizing and accessing your data efficiently.

Solution 1

Given the following dataframe:

col1 col2 col3 col4
0 A B C D
1 E F NaN H
2 I J Z Y
3 S X E V
4 Q A B W

Perform the following operations:

a) Sort the index.

b) Sort by a single column col1.

c) Sort by col1 in descending order.

d) Sort by two columns, col1 and col2.

Sort the index

Python 3.10.4
import pandas as pd
import numpy as np
df=pd.DataFrame({
"": ['A','B','C','D'],
"col1": ['E','F',np.NaN, 'H'],
"col2": ['I','J','Z','Y'],
"col3": ['S','X','E','V'],
"col4": ['Q', 'A','B','W']
})
print(df.sort_index(axis='columns'))
  • Line 12: We sort the DataFrame df by the column indices. It rearranges the columns in the DataFrame in alphabetical order.

Sort

...