Return list of indices/index where a min/max value occurs in a pandas dataframe

后端 未结 1 1806
鱼传尺愫
鱼传尺愫 2021-01-15 01:42

I\'d like to search a pandas DataFrame for minimum values. I need the min in the entire dataframe (across all values) analogous to df.min().min().

1条回答
  •  醉梦人生
    2021-01-15 02:11

    Based on your revised update:

    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
    

    Then the following would work:

    In [211]:
    df[df==df.min().min()].dropna(axis=1, thresh=1).dropna()
    
    Out[211]:
         x    y
    2 -1.0 -1.0
    

    So this uses the boolean mask on the 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
    

    and we call dropna with param thresh=1 this drops columns that don't have at least 1 non-NaN value:

    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
    

    Probably safer to call again with 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
    

    0 讨论(0)
提交回复
热议问题