基于多个列值的功能的DataFrame排序 [英] DataFrame sorting based on a function of multiple column values
本文介绍了基于多个列值的功能的DataFrame排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出:
from pandas import DataFrame
import pandas as pd
d = {'x':[2,3,1,4,5],
'y':[5,4,3,2,1],
'letter':['a','a','b','b','c']}
df = DataFrame(d)
df然后看起来像这样:
df then looks like this:
df:
letter x y
0 a 2 5
1 a 3 4
2 b 1 3
3 b 4 2
4 c 5 1
我想要类似的东西:
f = lambda x,y: x**2 + y**2
test = df.sort(f('x', 'y'))
这应该根据"x"和"y"列的平方值的总和对整个数据帧进行排序,然后给我:
This should order the complete dataframe with respect to the sum of the squared values of column 'x' and 'y' and give me:
test:
letter x y
2 b 1 3
3 b 4 2
1 a 3 4
4 c 5 1
0 a 2 5
升序或降序无关紧要.有没有一个很好的简单方法来做到这一点?我还找不到解决方法.
Ascending or descending order does not matter. Is there a nice and simple way to do that? I could not yet find a solution.
推荐答案
df.iloc[(df.x ** 2 + df.y **2).sort_values().index]
这篇关于基于多个列值的功能的DataFrame排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文