Pandas pivot_table, sort values ​​by columns

I am a new Pandas user and I like it!

I am trying to create a pivot table in Pandas. As soon as I have a pivot table, as I want, I would like to rank the values ​​in columns.

I attached the image from Excel, as in a tabular format it is easier to see what I am trying to achieve. Image link

I searched through stackoverflow, but it's hard for me to find the answer. I tried using .sort () but this will not work. Any help would be appreciated.

Thanks in advance

+4
source share
1 answer

This should do what you are looking for:

In [1]: df = pd.DataFrame.from_dict([{'Country': 'A', 'Year':2012, 'Value': 20, 'Volume': 1}, {'Country': 'B', 'Year':2012, 'Value': 100, 'Volume': 2}, {'Country': 'C', 'Year':2013, 'Value': 40, 'Volume': 4}])

In [2]: df_pivot = pd.pivot_table(df, index=['Country'], columns = ['Year'],values=['Value'], fill_value=0)

In [3]: df_pivot
Out [4]:
    Value     
Year     2012 2013
Country           
A          20    0
B         100    0
C           0   40

In [5]: df = df.reindex(df_pivot['Value'].sort_values(by=2012, ascending=False).index)

Out [6]: 
    Value     
Year     2012 2013
Country           
B         100    0
A          20    0
C           0   40

.

+7

Source: https://habr.com/ru/post/1663612/


All Articles