1/ Original data in excel
I have a data frame with these data values as shown below:
2/ Coding
Loading this excel into a data frame, wrote a pivot_table code to index the category and display the count of transactions for each month.
This is the code:
loadexpense_df = pd.read_excel("C:ExpensesTestData.xlsx")
month_df = pd.pivot_table(loadexpense_df,index="Category",columns="Month",aggfunc={"Month":len}, fill_value=0)
The result of month_df as shown below:
3/ Question
I would want to arrange the month colunms in this order: Feb, Mar, Apr and so on. Is this possible to do?
Thanks for the guidance
First, see your current columns:
cols = month_df.columns.tolist()
I think your cols
should be like this now:
[('Month', 'Apr'), ('Month', 'Aug'), ...]
so you can reorder your cols
like this:
month_names = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
cols = sorted(cols, key=lambda x: month_names.index(x[1]))
and finally set the months_df with new columns ordering:
month_df = month_df[cols]
And I think its done.
You can read more about reordering columns in this question .
IIUC:
You need to reindex the axis in the order you want. There is a method known as reindex_axis
I am assuming you have the name of the columns:
IF NO:
column_list = month_df.columns.tolist()
Access the month name using:
column_list.index(x[1])
If YES
order_of_column = ['Feb', 'Mar', 'Apr','May', 'Jun', 'Jul', 'Aug']
month_df1 = month_df.reindex_axis(order_of_column, axis=1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.