如何在多索引数据框中随机打乱外部索引,而将内部索引按升序排列



下面的代码段生成了一个示例数据帧:

fruits=pd.DataFrame()
fruits['month']=['jan','feb','feb','march','jan','april','april','june','march','march','june','april']
fruits['fruit']=['apple','orange','pear','orange','apple','pear','cherry','pear','orange','cherry','apple','cherry']
ind_mnth=fruits['month'].values
ind_fruit=fruits['fruit'].values
fruits['price']=[30,20,40,25,30 ,45,60,45,25,55,37,60]
fruits_grp = fruits.set_index([ind_mnth, ind_fruit],drop=False)

在多索引数据框架中,如何随机打乱外部索引和内部索引的升序排列?

你可以尝试这样做:

mnths = fruits.drop_duplicates(subset=['month']).sample(frac=1).reset_index().month.unique()
fruits.groupby(['month','fruit'])['price'].sum().loc[mnths]

首先对数据框中的月份进行随机排序,然后按月份和水果分组,这将按字母顺序排序,然后使用随机排序的月份列表

进行索引

最新更新