...

/

Solution: Sorting, Columns, Filtering, and Indexing Operations

Solution: Sorting, Columns, Filtering, and Indexing Operations

See the solution to problems related to sorting, columns, filtering and indexing operations.

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

...