Generate combinations with specified order with itertools.combinations

Viewed 58

I used itertools.combinations to generate combinations for a dataframe's index. I'd like the combinations in specified order --> (High - Mid - Low)

Example

from itertools import combinations
d = {'levels':['High', 'High', 'Mid', 'Low', 'Low', 'Low', 'Mid'], 'converted':[True, True, True, False, False, True, False]}
df = pd.DataFrame(data=d)
df_ = pd.crosstab(df['levels'], df['converted'])

df_

converted   False   True
levels      
High        0       2
Low         2       1
Mid         1       1

list(combinations(df_.index, 2)) returns [('High', 'Low'), ('High', 'Mid'), ('Low', 'Mid')]

I'd like the third group to be ('Mid', 'Low'), how can I achieve this ?

1 Answers

Use DataFrame.reindex first, but first and second values in list are swapped:

order = ['High','Mid','Low']
a = list(combinations(df_.reindex(order).index, 2))
print (a)
[('High', 'Mid'), ('High', 'Low'), ('Mid', 'Low')]
Related