Sort pandas dataframe both on values of a column and index?

后端 未结 8 1577
被撕碎了的回忆
被撕碎了的回忆 2020-12-13 08:43

Is it feasible to sort pandas dataframe by values of a column, but also by index?

If you sort a pandas dataframe by values of a column, you can get the resultant dat

相关标签:
8条回答
  • 2020-12-13 09:26

    I believe that the original order from sort_values is kept even when sort_index is applied, so this should work:

    df.sort_values('count', ascending=False).sort_index(level=[index_level1, index_level2])
    
    0 讨论(0)
  • 2020-12-13 09:32

    You can use a combination of groupby and apply:

    In [2]: df = pd.DataFrame({
                'transID':  range(8),
                'Location': ['New York','Chicago','New York','New York','Atlanta','Los Angeles',
                                'Chicago','Atlanta'],
                'Sales':    np.random.randint(0,10000,8)}).set_index('transID')
    In [3]: df
    Out[3]:
            Location    Sales
    transID
    0       New York    1082
    1       Chicago     1664
    2       New York    692
    3       New York    5669
    4       Atlanta     7715
    5       Los Angeles 987
    6       Chicago     4085
    7       Atlanta     2927
    
    In [4]: df.groupby('Location').apply(lambda d: d.sort()).reset_index('Location',drop=True)
    Out[4]:
            Location    Sales
    transID
    4       Atlanta     7715
    7       Atlanta     2927
    1       Chicago     1664
    6       Chicago     4085
    5       Los Angeles 987
    0       New York    1082
    2       New York    692
    3       New York    5669
    

    I drop 'Location' at in the last line because groupby inserts the grouped levels into the first positions in the index. Sorting and then dropping them preserves the sorted order.

    0 讨论(0)
提交回复
热议问题