gpt4 book ai didi

python - Pandas 数据框 : return row AND column of maximum value(s)

转载 作者:太空狗 更新时间:2023-10-30 02:10:48 25 4
gpt4 key购买 nike

我有一个数据框,其中所有值都具有相同的种类(例如,相关矩阵——但我们希望其中有一个唯一的最大值)。我想返回该矩阵最大值的行和列。

我可以通过更改

的第一个参数来获得跨行 列的最大值
df.idxmax()

但是我还没有找到合适的方法来返回整个数据帧最大值的行/列索引。

例如,我可以在 numpy 中这样做:

>>>npa = np.array([[1,2,3],[4,9,5],[6,7,8]])
>>>np.where(npa == np.amax(npa))
(array([1]), array([1]))

但是当我在 pandas 中尝试类似的东西时:

>>>df = pd.DataFrame([[1,2,3],[4,9,5],[6,7,8]],columns=list('abc'),index=list('def'))
>>>df.where(df == df.max().max())
a b c
d NaN NaN NaN
e NaN 9 NaN
f NaN NaN NaN

在第二个层次上,我真正想做的是返回前 n 个值的行和列,例如作为一个系列。

例如对于以上内容,我想要一个功能:

>>>topn(df,3)
b e
c f
b f
dtype: object
>>>type(topn(df,3))
pandas.core.series.Series

甚至只是

>>>topn(df,3)
(['b','c','b'],['e','f','f'])

一个 numpy.where()

最佳答案

我想通了第一部分:

npa = df.as_matrix()   
cols,indx = np.where(npa == np.amax(npa))
([df.columns[c] for c in cols],[df.index[c] for c in indx])

现在我需要一种方法来获得前 n 个。一个幼稚的想法是复制数组,并用 NaN 迭代替换顶部值,并在您进行时获取索引。似乎效率低下。有没有更好的方法来获取 numpy 数组的前 n 个值?还好如图here有,通过 argpartition,但我们必须使用扁平化索引。

def topn(df,n):
npa = df.as_matrix()
topn_ind = np.argpartition(npa,-n,None)[-n:] #flatend ind, unsorted
topn_ind = topn_ind[np.argsort(npa.flat[topn_ind])][::-1] #arg sort in descending order
cols,indx = np.unravel_index(topn_ind,npa.shape,'F') #unflatten, using column-major ordering
return ([df.columns[c] for c in cols],[df.index[i] for i in indx])

在示例中尝试这个:

>>>df = pd.DataFrame([[1,2,3],[4,9,5],[6,7,8]],columns=list('abc'),index=list('def'))
>>>topn(df,3)
(['b', 'c', 'b'], ['e', 'f', 'f'])

随心所欲。请注意,排序最初不是要求的,但如果 n 不大,则提供的开销很小。

关于python - Pandas 数据框 : return row AND column of maximum value(s),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26880989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com