Skip to content Skip to sidebar Skip to footer

Pandas: Sort Innermost Column Group-wise Based On A Multilevel Column Excluding One Row Which Matches A Certain Substring

This is an extension to my previous question: Below df: In [225]: df = pd.DataFrame({'A': ['a'] * 12, ...: 'B': ['b'] * 12, ...: 'C': ['C1',

Solution 1:

Use Index.get_level_values with str.contains for test all:

lvls = list(x.index.names[:-1])
print (lvls)
['B', 'C']

x[('tmp', 'tmp')] = pd.to_numeric(x[('E','a')].str.get('value'), errors='coerce')

x[('max','tmp')] = x.index.get_level_values(-1).str.contains('all')


x1 = x.sort_values(lvls + [('max','tmp'), ('tmp','tmp')])
print (x1)
                                                 E   tmp    max
A                                                a   tmp    tmp
B C  D                                                         
b C1 D1         {'value': '4', 'percentage': None}   4.0False
     D2           {'value': 5, 'percentage': None}   5.0False
     D3           {'value': 9, 'percentage': None}   9.0False
     x:all:1    {'value': '9', 'percentage': None}   9.0True
  C2 D3          {'value': 11, 'percentage': None}  11.0False
     D1          {'value': 12, 'percentage': None}  12.0False
     D4                                         {}   NaN  False0:1:all     {'value': 33, 'percentage': None}  33.0True
  C3 D1          {'value': 12, 'percentage': None}  12.0False
     D3        {'value': '12', 'percentage': None}  12.0False
     D2       {'value': 'N/A', 'percentage': None}   NaN  Falseall         {'value': 24, 'percentage': None}  24.0True

And:

x2 = x.sort_values(lvls + [('max','tmp'), ('tmp','tmp')],
                   ascending=[True] * len(lvls) + [True, False])
print (x2)
                                                 E   tmp    max
A                                                a   tmp    tmp
B C  D                                                         
b C1 D3           {'value': 9, 'percentage': None}   9.0False
     D2           {'value': 5, 'percentage': None}   5.0False
     D1         {'value': '4', 'percentage': None}   4.0False
     x:all:1    {'value': '9', 'percentage': None}   9.0True
  C2 D1          {'value': 12, 'percentage': None}  12.0False
     D3          {'value': 11, 'percentage': None}  11.0False
     D4                                         {}   NaN  False0:1:all     {'value': 33, 'percentage': None}  33.0True
  C3 D1          {'value': 12, 'percentage': None}  12.0False
     D3        {'value': '12', 'percentage': None}  12.0False
     D2       {'value': 'N/A', 'percentage': None}   NaN  Falseall         {'value': 24, 'percentage': None}  24.0True

Last remove helper columns:

x1 = x1.drop([('max','tmp'), ('tmp','tmp')], axis=1)
x2 = x2.drop([('max','tmp'), ('tmp','tmp')], axis=1)

Post a Comment for "Pandas: Sort Innermost Column Group-wise Based On A Multilevel Column Excluding One Row Which Matches A Certain Substring"