R的哪个()和which.min()相当于Python

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


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

我在这里阅读了类似的主题。我认为问题不同或至少.index()无法解决我的问题。

This is a simple code in R and its answer:

这是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

Which simply returns the index of the item which meets the condition.

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

If x be the input for Python, how can I get the indeces for the elements which meet criteria x==2 and the one which is the smallest in the array which.min.

如果x是Python的输入,我如何获得符合条件x == 2的元素的indeces和数组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'

4 个解决方案

#1


8  

Numpy does have built-in functions for it

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

#2


3  

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

这里有一个实例

#3


1  

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).

您还可以使用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)

Returns [4, 0]

返回[4,0]

#4


1  

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

NumPy for R为您提供了Python中的一系列R功能。

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]),)
智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2018/01/30/6f9e77753fbb0713c23883aee9ecc7f6.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告