Created
October 2, 2019 22:32
Pandas: Sort within groups
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Load the Pandas libraries with alias 'pd' | |
import pandas as pd | |
# Read csv to dataframe | |
df = pd.read_csv("data.csv") | |
# Set column types | |
df['Submission Date'] = pd.to_datetime(df['Submission Date'], format="%Y-%m-%d %H:%M") | |
print(df) | |
# Steps: | |
# 1. Sort 'Project Name' column alphabetically | |
# 2. Group by 'Project Name' | |
# 3. Sort within each group by 'Submission Date' | |
df = df.sort_values(['Project Name'], ascending=True) \ | |
.groupby(['Project Name'], sort=False) \ | |
.apply(lambda x: x.sort_values(['Submission Date'], ascending=True)) \ | |
.reset_index(drop=True) | |
print(df) | |
df.to_csv('out.csv', encoding='utf-8', index=False) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment