blacktj
blacktj

Reputation: 173

Pandas pivot_table force column structure?

I have a dataframe I want to summarize and send in an email, is there any way to explicitly pass the columns IN THE ORDER I want them displayed?

df.pivot_table(index='Owner', values=['Matches', 'W', 'D', 'L', 'Pts'], aggfunc=sum)

returns this column order (index, sorted value columns a-z): Owner, D, L, Matches, Pts, W

Currently doing this in two-ish operations:

values_cols = ['Matches', 'W', 'D', 'L', 'Pts']
df2 = df.pivot_table(index='Owner', values=values_cols, aggfunc=sum)
df2 = df2.loc[:,values_cols]

Just curious if I am doing something wrong or is this expected behavior?

Tried sort=False, then checked the pivot_table documentation..

Upvotes: 0

Views: 356

Answers (1)

IoaTzimas
IoaTzimas

Reputation: 10624

You can do it with pivot_table adding reindex at the end:

result = pd.pivot_table(df, index='Owner', values=values_cols, aggfunc=sum).reindex(columns=values_cols)

Upvotes: 1

Related Questions