擅长:python、mysql、java
<p>有多种方法可以做到这一点。其中一种方法是计算要排序的度量(总预算),对数据帧排序,然后删除新创建的变量。你知道吗</p>
<p>我们必须重置原始数据帧的索引才能正确合并。你知道吗</p>
<pre><code>#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'])
</code></pre>
<p>最终输出如下</p>
<pre><code> 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
</code></pre>
<p>除此之外,一个更紧凑的解决方案是</p>
<pre><code>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'])
</code></pre>
<p>这里,<code>out</code>也给出了与前面相同的输出。你知道吗</p>