在pandas数据帧的不同列上有效地组合min / max

问题描述 投票:1回答:1

我有一个包含计算结果的pandas数据框,需要:

  • 获取列的最大值,并为该值查找另一列的最大值
  • 获取列的最小值,并为该值查找另一列的最大值

有更有效的方法吗?

建立

metrictuple = namedtuple('metrics', 'prob m1 m2')
l1 =[metrictuple(0.1, 0.4, 0.04),metrictuple(0.2, 0.4, 0.04),metrictuple(0.4, 0.4, 0.1),metrictuple(0.7, 0.2, 0.3),metrictuple(1.0, 0.1, 0.5)]
df = pd.DataFrame(l1)
# df
#   prob   m1    m2
#0   0.1  0.4  0.04
#1   0.2  0.4  0.04
#2   0.4  0.4  0.10
#3   0.7  0.2  0.30
#4   1.0  0.1  0.50

tmp = df.loc[(df.m1.max() == df.m1), ['prob','m1']]
res1 = tmp.loc[tmp.prob.max() == tmp.prob, :].to_records(index=False)[0]
#(0.4, 0.4)
tmp = df.loc[(df.m2.min() == df.m2), ['prob','m2']]
res2 = tmp.loc[tmp.prob.max() == tmp.prob, :].to_records(index=False)[0]
#(0.2, 0.04)
python python-3.x pandas
1个回答
1
投票

大熊猫不适合数值计算。这是因为切片和选择数据会产生很大的开销,在本例中为df.loc

好消息是pandasnumpy很好地交互,所以你可以很容易地下降到底层的numpy阵列。

下面我定义了一些帮助函数,使代码更具可读性。请注意,numpy切片是通过从0开始的行号和列号执行的。

arr = df.values

def arr_max(x, col):
    return x[x[:,col]==x[:,col].max()]

def arr_min(x, col):
    return x[x[:,col]==x[:,col].min()]

res1 = arr_max(arr_max(arr, 1), 0)[:,:2]     # array([[ 0.4,  0.4]])
res2 = arr_max(arr_min(arr, 2), 0)[:,[0,2]]  # array([[ 0.2 ,  0.04]])
© www.soinside.com 2019 - 2024. All rights reserved.