【问题标题】:R's which() and which.min() Equivalent in PythonR 的 which() 和 which.min() 在 Python 中等价
【发布时间】:2018-07-09 04:47:04
【问题描述】:

我阅读了类似的主题here。我认为问题有所不同,或者至少.index() 无法解决我的问题。

这是 R 中的一个简单代码及其答案:

x <- c(1:4, 0:5, 11)
x
#[1]  1  2  3  4  0  1  2  3  4  5 11
which(x==2)
# [1] 2 7
min(which(x==2))
# [1] 2
which.min(x)
#[1] 5

它只是返回满足条件的项目的索引。

如果x 是Python 的输入,我怎样才能得到满足条件x==2 和数组which.min 中最小的元素的索引。

x = [1,2,3,4,0,1,2,3,4,11] 
x=np.array(x)
x[x>2].index()
##'numpy.ndarray' object has no attribute 'index'

【问题讨论】:

    标签: python r numpy


    【解决方案1】:

    一个简单的循环就可以了:

    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)
    

    一个理解的班轮:

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

    你有一个live example

    【讨论】:

    • 所以没有办法代替循环?内置函数?
    • 没有内置的python,可能是numpy中的东西
    【解决方案2】:

    Numpy 确实有它的内置函数

    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
    

    【讨论】:

      【解决方案3】:

      您也可以使用heapq 来查找最小的索引。然后您可以选择查找多个(例如 2 个最小的索引)。

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

      返回 [4, 0]

      【讨论】:

        【解决方案4】:

        NumPy for R 在 Python 中为您提供了一堆 R 功能。

        关于您的具体问题:

        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]),)
        

        【讨论】:

        • 例如,如果你有一个 3x3 矩阵,你会怎么做?我喜欢你对 R 和 Python 的比较,这对于 R 专家的用户非常有用,但像我这样的 Python 初学者用户非常有用
        【解决方案5】:

        基于python索引和numpy的方法,根据最小/最大值的索引返回所需列的值

        df.iloc[np.argmin(df['column1'].values)]['column2']
        

        【讨论】:

        • 谢谢。它适用于 pandas.DataFrame。我的例子是一个简单的数组。
        【解决方案6】:

        内置的index函数可用于此目的:

        x = [1,2,3,4,0,1,2,3,4,11] 
        print(x.index(min(x)))
        #4
        print(x.index(max(x)))
        #9
        

        但是,对于基于条件的索引,np.where 或手动循环和enumerate 可能会起作用:

        index_greater_than_two1 = [idx for idx, val in enumerate(x) if val>2]
        print(index_greater_than_two1)
        # [2, 3, 7, 8, 9]
        
        # OR
        
        index_greater_than_two2 = np.where(np.array(x)>2)
        print(index_greater_than_two2)
        # (array([2, 3, 7, 8, 9], dtype=int64),)
        

        【讨论】:

          猜你喜欢
          • 2014-09-25
          • 1970-01-01
          • 2017-11-27
          • 1970-01-01
          • 1970-01-01
          • 2020-09-14
          • 2018-07-18
          • 2016-06-14
          相关资源
          最近更新 更多