pandas 排序lambda函数

编程入门 行业动态 更新时间:2024-10-27 02:19:26
本文介绍了 pandas 排序lambda函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

给出具有3列A,B,C和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函数

本文发布于:2023-11-28 09:23:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641836.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   pandas   lambda

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!