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

Had*_*dij 11 python numpy r which

我在这里阅读了类似的主题.我认为问题不同或者至少.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
Run Code Online (Sandbox Code Playgroud)

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

如果x是Python的输入,我如何获得符合条件的元素的indeces 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'
Run Code Online (Sandbox Code Playgroud)

ero*_*oar 18

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
Run Code Online (Sandbox Code Playgroud)


Net*_*ave 5

一个简单的循环即可:

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)
Run Code Online (Sandbox Code Playgroud)

一班具有理解力的班轮:

res = [i for i, v in enumerate(x) if check_condition(v)]
Run Code Online (Sandbox Code Playgroud)

这里有一个现场例子