pandas 排序lambda函数 [英] pandas sort lambda function

查看:94
本文介绍了 pandas 排序lambda函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出具有3列ABC和3行数值的数据框a.如何仅使用A[i]*B[i]的乘积使用comp运算符对所有行进行排序.熊猫排序似乎只接受列,然后采用排序方法.
我想使用下面的比较功能.

Given a dataframe a with 3 columns, A , B , C and 3 rows of numerical values. How does one sort all the rows with a comp operator using only the product of A[i]*B[i]. It seems that the pandas sort only takes columns and then a sort method.
I would like to use a comparison function like below.

f = lambda i,j: a['A'][i]*a['B'][i] < a['A'][j]*a['B'][j]

推荐答案

至少有两种方法:

方法1

假设您从

In [175]: df = pd.DataFrame({'A': [1, 2], 'B': [1, -1], 'C': [1, 1]})

您可以添加一列作为您的排序键

You can add a column which is your sort key

In [176]: df['sort_val'] = df.A * df.B

最后按其排序并将其删除

Finally sort by it and drop it

In [190]: df.sort_values('sort_val').drop('sort_val', 1)
Out[190]: 
   A  B  C
1  2 -1  1
0  1  1  1

方法2

使用 numpy.argsort ,然后使用.ix生成的索引:

In [197]: import numpy as np

In [198]: df.ix[np.argsort(df.A * df.B).values]
Out[198]: 
   A  B  C
0  1  1  1
1  2 -1  1

这篇关于 pandas 排序lambda函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆