「decil_score」という列に対して、「グループ」+「数字」の順になっているのですが、
これを上から「グループ1」「グループ2」…「グループn」という昇順にしたいです。
★TotalPrice、Ratioの値を利用した昇順は避けたい
★あくまでも「グループ〇」の数字でソートしたい
どなたかご教授頂けませんでしょうか
#今回利用するデータセットA df = A #同じCustomerIDを持つ場合は、TotalPriceをまとめる df1 = df[['CustomerID', 'TotalPrice']].groupby('CustomerID').sum() #TotalPriceの降順に並び替え df2 = df1.sort_values(by='TotalPrice', ascending=False).reset_index() #並び替えたデータをn等分する(今回はn=14) df2['decil_value'] = pd.qcut(df2['TotalPrice'], 14, duplicates = 'drop') #n等分されたデータに対して、同じグループに所属する場合は、「グループ〇」という名前を付ける categories = df2['decil_value'].cat.categories.sort_values(ascending=False) categories = dict(zip(categories, [f'グループ{i+1}' for i in range(len(categories))])) df2['decil_score'] = df2['decil_value'].map(categories) #同じグループ名のデータをまとめる df3 = df2.groupby('decil_score').sum().reset_index() #全体売上に対する割合を出す df3['Ratio'] = (df3['TotalPrice'] / df['TotalPrice'].sum()) #「データ〇」の昇順に並べ替えたい df4 = sorted(df3['decil_score'], key=lambda x: int(re.search(r'\d+', x).group())) コード

バッドをするには、ログインかつ
こちらの条件を満たす必要があります。