本文介绍了 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函数
发布评论