【问题标题】:Return list of indices/index where a min/max value occurs in a pandas dataframe返回熊猫数据框中出现最小值/最大值的索引/索引列表
【发布时间】:2016-07-19 21:45:58
【问题描述】:

我想在 pandas DataFrame 中搜索最小值。我需要整个数据帧(所有值)中的最小值,类似于df.min().min()。但是,我还需要知道该值出现的位置的索引。

我尝试了许多不同的方法:

  • df.where(df == (df.min().min())),
  • df.where(df == df.min().min()).notnull()(source) 和
  • val_mask = df == df.min().min(); df[val_mask] (source)。

这些返回非最小值/布尔值的 NaN 数据框,但我无法找到获取这些位置的 (row, col) 的方法。

有没有更优雅的方法来搜索数据框的最小值/最大值并返回包含所有出现位置的列表?

import pandas as pd

keys = ['x', 'y', 'z']
vals = [[1,2,-1], [3,5,1], [4,2,3]]
data = dict(zip(keys,vals))
df = pd.DataFrame(data)

list_of_lowest = []

for column_name, column in df.iteritems():
    if len(df[column == df.min().min()]) > 0:
        print(column_name, column.where(column ==df.min().min()).dropna())
        list_of_lowest.append([column_name, column.where(column ==df.min().min()).dropna()])

list_of_lowest
output: [['x', 2   -1.0
Name: x, dtype: float64]]

【问题讨论】:

  • 抱歉,您刚刚将以下内容的输出:df[df==df.max().max()].dropna(axis=1, thresh=1).dropna() 转换为列表?
  • @EdChum 是的!谢谢,这正是我所追求的。你能解释一下 thresh=1 参数的作用吗?我不明白文档“需要许多非 NA 值”的意思..

标签: python pandas


【解决方案1】:

根据您修改后的更新:

In [209]:
keys = ['x', 'y', 'z'] 
vals = [[1,2,-1], [3,5,-1], [4,2,3]] 
data = dict(zip(keys,vals)) 
df = pd.DataFrame(data)
df

Out[209]:
   x  y  z
0  1  3  4
1  2  5  2
2 -1 -1  3

然后以下将起作用:

In [211]:
df[df==df.min().min()].dropna(axis=1, thresh=1).dropna()

Out[211]:
     x    y
2 -1.0 -1.0

所以这使用了 df 上的布尔掩码:

In [212]:
df[df==df.min().min()]

Out[212]:
     x    y   z
0  NaN  NaN NaN
1  NaN  NaN NaN
2 -1.0 -1.0 NaN

我们使用参数thresh=1 调用dropna,这会删除没有至少1 个非NaN 值的列:

In [213]:
df[df==df.min().min()].dropna(axis=1, thresh=1)

Out[213]:
     x    y
0  NaN  NaN
1  NaN  NaN
2 -1.0 -1.0

使用thresh=1 再次调用可能更安全:

In [214]:
df[df==df.min().min()].dropna(axis=1, thresh=1).dropna(thresh=1)

Out[214]:
     x    y
2 -1.0 -1.0

【讨论】:

  • 几乎,理想情况下,如果它可以在极端情况下工作,例如:values. keys = ['x', 'y', 'z'] vals = [[1,2,-1], [3,5,-1], [4,2,3]] data = dict(zip(keys,vals)) df = pd.DataFrame(data),我更喜欢你的回答 cmets。可以在这里添加吗?
猜你喜欢
  • 2013-02-03
  • 2021-06-23
  • 2019-11-01
  • 2018-08-04
  • 2022-07-25
  • 2021-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多