简体   繁体   English

根据列的总和对熊猫数据框进行排序

[英]Sorting a pandas dataframe based on the sum of columns

I have got the following code which creates the dataframe shown in the attached image:我有以下代码创建附件图像中显示的数据框:

d = []

for i in range(5): 
    d.append({
                'a': np.random.rand(), 
                'b': np.random.rand(), 
                'c': np.random.rand(), 
                'd': np.random.rand(), 

                })

d = pd.DataFrame(d)

I would like to sort this in ascending order based on the sum of the 'c' and 'd' columns.我想根据“c”和“d”列的总和按升序对它进行排序。

The final dataframe should still have 4 columns but just in sorted order.最终的数据框应该仍然有 4 列,但只是按排序顺序。

I know pandas.DataFrame.sort_values exists but not sure how to use it for my case.我知道pandas.DataFrame.sort_values存在,但不确定如何在我的情况下使用它。

Thankyou.谢谢你。

在此处输入图像描述

d['e'] = d["c"] + d["d"]
d.sort_values("e").drop("e", axis=1, inplace=True)

Also, this SO link show how to do this without creating a new column https://stackoverflow.com/a/71776590/14066512此外,此 SO 链接显示如何在不创建新列的情况下执行此操作https://stackoverflow.com/a/71776590/14066512

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM