how to get the unique combination of columns and sort by them in python data frame?
Question: how to get the unique combination of columns and sort by them in python data
frame? I know I can use df.groupby(['col1','col2']).size() to get the unique
combination. However, I also want to have the result order by the ascending
order of col2, and then ascending order by col1. For example, if my dataframe
is like this:

    
    
      col1  col2
    0    A     1
    1    B     3
    2    C     2
    3    D     1
    4    A     1
    5    F     2
    

I would like the final output look like this:

    
    
      col1  col2 
    0    A     1 
    1    D     1 
    2    C     2
    3    F     2
    4    B     3 
    


Answer: Use [`groupby`](http://pandas.pydata.org/pandas-
docs/stable/generated/pandas.DataFrame.groupby.html) by `col2` and `col1`, but
then need [`swaplevel`](http://pandas.pydata.org/pandas-
docs/stable/generated/pandas.DataFrame.swaplevel.html) (if order columns
`col1` and `col2` is important) with
[`reset_index`](http://pandas.pydata.org/pandas-
docs/stable/generated/pandas.DataFrame.reset_index.html) \- solution use
default sorting in `groupby`:

    
    
    df1 = df.groupby(['col2','col1']).size().swaplevel(0,1).reset_index(name='count')
    print (df1)
      col1  col2  count
    0    A     1      2
    1    D     1      1
    2    C     2      1
    3    F     2      1
    4    B     3      1
    

Second solution need first [`sort_values`](http://pandas.pydata.org/pandas-
docs/stable/generated/pandas.DataFrame.sort_values.html) in columns `col2` and
`col1` and then add parameter `sort=False` to
[`groupby`](http://pandas.pydata.org/pandas-
docs/stable/generated/pandas.DataFrame.groupby.html), because by default
`sort=True`:

    
    
    df = df.sort_values(['col2','col1'])
    print (df)
      col1  col2
    0    A     1
    4    A     1
    3    D     1
    2    C     2
    5    F     2
    1    B     3
    
    print (df.groupby(['col1','col2'], sort=False).size())
    col1  col2
    A     1       2
    D     1       1
    C     2       1
    F     2       1
    B     3       1
    dtype: int64
    

Another solution is first [`groupby`](http://pandas.pydata.org/pandas-
docs/stable/generated/pandas.DataFrame.groupby.html) and then
[`sort_values`](http://pandas.pydata.org/pandas-
docs/stable/generated/pandas.DataFrame.sort_values.html):

    
    
    df1 = df.groupby(['col1','col2']).size().reset_index(name='count')
    print (df1)
      col1  col2  count
    0    A     1      2
    1    B     3      1
    2    C     2      1
    3    D     1      1
    4    F     2      1
    
    df1 = df1.sort_values(['col2','col1'])
    print (df1)
      col1  col2  count
    0    A     1      2
    3    D     1      1
    2    C     2      1
    4    F     2      1
    1    B     3      1
    

