RE-ORDER VALUES OF COLUMNS PARAMETERS
Question:
I’m using this code valores.pivot(index='MARCA', columns='MES_C', values=['CMC','CMV','VL_VENDAS'])
to pivot this dataframe on python withe pandas.
MARCA MES_C CMC CMV VL_VENDAS
3F 01/2022 0,00 33,85 147,70
3M 01/2022 57.130,75 77.457,69 182.964,37
3M 02/2022 87.177,66 75.491,39 169.560,01
but the columns='MES_C'
is out of order.
CMC CMV VL_VENDAS CMC CMV VL_VENDAS
MES_C 01/2022 01/2022 01/2022 02/2022 02/2022 02/2022
MARCA
3F 0,00 NaN 33,85 NaN 147,70 NaN
3M 5.130,75 7.177,66 7.457,69 5.491,39 2.964,37 9.560,01
how to change to get the result like this?
CMC CMV VL_VENDAS
MES_C 01/2022 02/2022 01/2022 02/2022 01/2022 02/2022
MARCA
3F 0,00 NaN 33,85 NaN 147,70 NaN
3M 57.130,75 87.177,66 77.457,69 75.491,39 182.964,37 169.560,01
I want to show the results groped by the values [‘CMC’,’CMV’,’VL_VENDAS’]
I’ved tried with
valores.pivot(index='MARCA', columns='MES_C', values=['CMC','CMV','VL_VENDAS'])
and
pd.pivot_table(valores, values=['CMC','CMV','VL_VENDAS'], index='MARCA', columns='MES_C', aggfunc='first')
Answers:
pivot = pd.pivot_table(valores, index=['MARCA'], columns='MES_C', aggfunc={'CMC':'sum','CMV':'sum','VL_VENDAS':'sum'}, fill_value=0, margins=True)
.swaplevel(axis=1)
.sort_index(level=0, axis=1)
.reindex(['CMC','CMV','VL_VENDAS'], level=1, axis=1)
.rename_axis(columns=[None, None])
pivot.to_excel('relatorio.xlsx', sheet_name='cmcxcmv')
with this code, works to change the column order and fix the problem.
I’m using this code valores.pivot(index='MARCA', columns='MES_C', values=['CMC','CMV','VL_VENDAS'])
to pivot this dataframe on python withe pandas.
MARCA MES_C CMC CMV VL_VENDAS
3F 01/2022 0,00 33,85 147,70
3M 01/2022 57.130,75 77.457,69 182.964,37
3M 02/2022 87.177,66 75.491,39 169.560,01
but the columns='MES_C'
is out of order.
CMC CMV VL_VENDAS CMC CMV VL_VENDAS
MES_C 01/2022 01/2022 01/2022 02/2022 02/2022 02/2022
MARCA
3F 0,00 NaN 33,85 NaN 147,70 NaN
3M 5.130,75 7.177,66 7.457,69 5.491,39 2.964,37 9.560,01
how to change to get the result like this?
CMC CMV VL_VENDAS
MES_C 01/2022 02/2022 01/2022 02/2022 01/2022 02/2022
MARCA
3F 0,00 NaN 33,85 NaN 147,70 NaN
3M 57.130,75 87.177,66 77.457,69 75.491,39 182.964,37 169.560,01
I want to show the results groped by the values [‘CMC’,’CMV’,’VL_VENDAS’]
I’ved tried with
valores.pivot(index='MARCA', columns='MES_C', values=['CMC','CMV','VL_VENDAS'])
and
pd.pivot_table(valores, values=['CMC','CMV','VL_VENDAS'], index='MARCA', columns='MES_C', aggfunc='first')
pivot = pd.pivot_table(valores, index=['MARCA'], columns='MES_C', aggfunc={'CMC':'sum','CMV':'sum','VL_VENDAS':'sum'}, fill_value=0, margins=True)
.swaplevel(axis=1)
.sort_index(level=0, axis=1)
.reindex(['CMC','CMV','VL_VENDAS'], level=1, axis=1)
.rename_axis(columns=[None, None])
pivot.to_excel('relatorio.xlsx', sheet_name='cmcxcmv')
with this code, works to change the column order and fix the problem.