Python Forum

Full Version: Need Help! Pandas EXCEL PIVOT
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I want to sort column 'PERIOD_START_TIME' from new date to old date.
df_pivot = pd.pivot_table (df, values = 'NTM NR RET NSA SN Total Drops',index = ['CELLCU'], columns = 'PERIOD_START_TIME', aggfunc = 'sum')
Output:
CELLCU 10/13/2022 10/14/2022 10/15/2022 10/16/2022 10/17/2022 A1WA0944C11 580 384 590 644 1464 A1WA0944C21 2065 3649 2687 2220 3205 A1WA0944C31 1874 1829 1901 2617 3111 A1WA6372A11 1327 1507 404 541 1478 A1WA6372A21 2559 35351 16881 9500 2203 A1WA6372A31 748 7422 563 914 1086 A1WA6374A11 84 93 1828 1339 414 A1WA6374A21 119 463 271 2245 628 A1WA6374A31 1532 6173 36461 78170 15273 A1WA6375A11 98 93 223 188 120
If this is a question about pivot tables, please provide a sample of the original data and describe the result you want after pivoting. Your problem might be solved by sorting the original dataframe before pivoting.

If you want to sort your pivoted dataframe columns:
from io import StringIO
import pandas as pd
from datetime import datetime

# Reproduce pivoted dataframe
csv_data= StringIO("""
CELLCU 10/13/2022 10/14/2022 10/15/2022 10/16/2022 10/17/2022
A1WA0944C11 580 384 590 644 1464
A1WA0944C21 2065 3649 2687 2220 3205
A1WA0944C31 1874 1829 1901 2617 3111
A1WA6372A11 1327 1507 404 541 1478
A1WA6372A21 2559 35351 16881 9500 2203
A1WA6372A31 748 7422 563 914 1086
A1WA6374A11 84 93 1828 1339 414
A1WA6374A21 119 463 271 2245 628
A1WA6374A31 1532 6173 36461 78170 15273
A1WA6375A11 98 93 223 188 120""")

df = pd.read_csv(csv_data, sep=" ")

# Sort columns[1:].  Month/Day/Year is not good for sorting.  Use datetime key.
columns = list(df.columns)
dates = sorted(columns[1:], key=lambda x:datetime.strptime(x, "%m/%d/%Y"), reverse=True)
df = df.reindex([columns[0]] + dates, axis=1)
print(df)