SORTING DATAFRAMES IN PANDAS
Listing 3.31 displays the contents of sort_df.py that illustrates how to sort the rows in a Pandas DataFrame.
LISTING 3.31: sort_df.py
import pandas as pd
df = pd.read_csv("duplicates.csv")
print("Contents of data frame:")
print(df)
print()
df.sort_values(by=['fname'], inplace=True)
print("Sorted (ascending) by first name:")
print(df)
print()
df.sort_values(by=['fname'], inplace=True,ascending=False)
print("Sorted (descending) by first name:")
print(df)
print()
df.sort_values(by=['fname','lname'], inplace=True)
print("Sorted (ascending) by first name and last name:")
print(df)
print()
Listing 3.31 initializes the DataFrame df with the contents of the CSV file duplicates.csv, and then displays the contents of the DataFrame. The next portion of Listing 3.31 displays the rows in ascending order based on the first name, and the next code block displays the rows in descending...