保持多个索引匹配的数据透视表排序

2024-03-28 13:03:02 发布

您现在位置:Python中文网/ 问答频道 /正文

是否可以对数据帧进行排序以保持索引之间的匹配?你知道吗

我的df:

             budget population
state   fu      
acre    ac1  600    50
        ac2  25     110
bahia   ba1  2300   80
        ba2   1     10
paulo   sp1  1000   100
        sp2  1000   230

我想得到以下结果,因为bahia指数的总预算更大:

             budget population
state   fu      
bahia   ba1  2300   80
        ba2   1     10
paulo   sp1  1000   100
        sp2  1000   230
acre    ac1  600    50
        ac2  25     110

但是在使用sort\u values()之后,我得到以下输出:

              budget population
state   fu      
bahia   ba1   2300   80
paulo   sp1   1000   100
        sp2   1000   230
acre    ac1   600    50
        ac2   25     110
bahia   ba2    1     10

我更新了问题以提供更多上下文


Tags: 数据排序budgetstatepopulationfusp2sp1
2条回答

有多种方法可以做到这一点。其中一种方法是计算要排序的度量(总预算),对数据帧排序,然后删除新创建的变量。你知道吗

我们必须重置原始数据帧的索引才能正确合并。你知道吗

#Creating the total budget variable
gp = df.groupby('state')['budget'].sum().reset_index()
gp.columns = ['state','total_budget']

#Merging with the total budget variable
out = df.reset_index().merge(gp, on='state')

#Sorting based on total_budget
out = out.sort_values('total_budget', ascending = False)
out.drop('total_budget',inplace = True, axis = 1)
out = out.set_index(['state','fu'])

最终输出如下

           budget  population
state fu                     
bahia ba1    2300          80
      ba2       1          10
paulo sp1    1000         100
      sp2    1000         230
acre  ac1     600          50
      ac2      25         110

除此之外,一个更紧凑的解决方案是

out = pd.concat([x[1] for x in sorted(df.reset_index().groupby('state'), key = lambda x : -np.sum(x[1].budget) )]).set_index(['state','fu'])

这里,out也给出了与前面相同的输出。你知道吗

这里有一种不计算总预算的排序方法。IIUC,这应该会返回您所需要的,即使有些州的总预算比其他州大,但预算较小。你知道吗

首先,我们将budget按状态分组。
其次,计算max预算。
第三,按降序排列这些值。
第四,取index这个新的Seriesstate名字。
最后,reindex用新的顺序适当地level我们原来的df。你知道吗

new_index = df["budget"]\
    .groupby("state")\
    .max()\
    .sort_values(ascending=False)\
    .index # just return the index

df.reindex(new_index, level=0)

输出:

           budget  population
state fu                     
bahia ba1    2300          80
      ba2       1          10
paulo sp1    1000         100
      sp2    1000         230
acre  ac1     600          50
      ac2      25         110

相关问题 更多 >