I have a dataframe that looks like this below:
but as you can see the dates are sorted by the Month without the year
I need it to look like this below:
Does anyone know a solution?
CodePudding user response:
Hope this helps
import pandas as pd
from datetime import datetime
col_names = df.keys()
col_in_datetime = [datetime.strptime(x, '%b-%y') for x in col_names]
sorted_in_datetime = sorted(col_in_datetime)
sorted_col_names = [x.strftime('%b-%y') for x in sorted_in_datetime]
df = df.reindex(sorted(sorted_col_names), axis=1)
CodePudding user response:
Move name column to index, Convert date column names to datetime and sort, Convert date column names back to original format, Move Name index back to column,
df = df.set_index("Name")
df.columns = [x.strftime("%b-%y") for x in sorted([pd.to_datetime(x, format="%b-%y", errors="coerce") for x in df.columns])]
df = df.reset_index()