python pandas-可以使用 where(max()) 比较 3 个相同形状的 dfs?这是掩蔽问题吗?

python pandas-possible to compare 3 dfs of same shape using where(max())? is this a masking issue?

我有一个包含 3 个相同形状的数据框的字典。我想创建:

  1. 第 4 个数据帧,它在每个坐标处标识原始 3 个中的最大值 - 所以 dic['four'].ix[0,'A'] = MAX( dic['one'].ix[0,'A'], dic['two'].ix[0,'A'], dic['three'].ix[0,'A'] )
  2. 第二大值第5

    dic = {}
    for i in ['one','two','three']:
        dic[i] = pd.DataFrame(np.random.randint(0,100,size=(10,3)), columns=list('ABC'))
    

我不知道如何使用 .where() 来比较原始的 3 个 dfs。对于最终数据集,循环将是低效的。

第一个问题很容易回答,您可以使用 numpy.maximum() 函数跨多个数据帧在每个单元格中找到元素方面的最大值

dic ['four'] = pd.DataFrame(np.maximum(dic['one'].values,dic['two'].values,dic['three'].values),columns = list('ABC'))

考虑 dict dfs 这是 pd.DataFrames

的字典
import pandas as pd
import numpy as np

np.random.seed([3,1415])
dfs = dict(
    one=pd.DataFrame(np.random.randint(1, 10, (5, 5))),
    two=pd.DataFrame(np.random.randint(1, 10, (5, 5))),
    three=pd.DataFrame(np.random.randint(1, 10, (5, 5))),
)

处理这个问题的最佳方法是使用 pd.Panel 对象,它是类似于 pd.DataFrame.

的高维对象
p = pd.Panel(dfs)

那么您需要的答案就非常简单

最大
p.max(axis='items')p.max(0)

倒数第
p.apply(lambda x: np.sort(x)[-2], axis=0)