R's which() and which.min() Equivalent in Python

前端 未结 5 960
囚心锁ツ
囚心锁ツ 2020-12-11 00:33

I read the similar topic here. I think the question is different or at least .index() couldnot solve my problem.

This is a simple code in R and its answ

相关标签:
5条回答
  • 2020-12-11 00:57

    You could also use heapq to find the index of the smallest. Then you can chose to find multiple (for example index of the 2 smallest).

    import heapq
    
    x = np.array([1,2,3,4,0,1,2,3,4,11]) 
    
    heapq.nsmallest(2, (range(len(x))), x.take)
    

    Returns [4, 0]

    0 讨论(0)
  • 2020-12-11 01:01

    NumPy for R provides you with a bunch of R functionalities in Python.

    As to your specific question:

    import numpy as np
    x = [1,2,3,4,0,1,2,3,4,11] 
    arr = np.array(x)
    print(arr)
    # [ 1  2  3  4  0  1  2  3  4 11]
    
    print(arr.argmin(0)) # R's which.min()
    # 4
    
    print((arr==2).nonzero()) # R's which()
    # (array([1, 6]),)
    
    0 讨论(0)
  • 2020-12-11 01:04

    Numpy does have built-in functions for it

    x = [1,2,3,4,0,1,2,3,4,11] 
    x=np.array(x)
    np.where(x == 2)
    np.min(np.where(x==2))
    np.argmin(x)
    
    np.where(x == 2)
    Out[9]: (array([1, 6], dtype=int64),)
    
    np.min(np.where(x==2))
    Out[10]: 1
    
    np.argmin(x)
    Out[11]: 4
    
    0 讨论(0)
  • 2020-12-11 01:09

    A simple loop will do:

    res = []
    x = [1,2,3,4,0,1,2,3,4,11] 
    for i in range(len(x)):
        if check_condition(x[i]):
            res.append(i)
    

    One liner with comprehension:

    res = [i for i, v in enumerate(x) if check_condition(v)]
    

    Here you have a live example

    0 讨论(0)
  • 2020-12-11 01:24

    The method based on python indexing and numpy, which returns the value of the desired column based on the index of the minimum/maximum value

    df.iloc[np.argmin(df['column1'].values)]['column2']
    
    0 讨论(0)
提交回复
热议问题