R在Python中等同于which()和which.min() [英] R's which() and which.min() Equivalent in Python

查看:431
本文介绍了R在Python中等同于which()和which.min()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在此处阅读了类似的主题.我认为问题不同,或者至少.index()无法解决我的问题.

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

这是R语言中的简单代码及其答案:

This is a simple code in R and its answer:

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.

如果x是Python的输入,我如何获得满足条件x==2的元素和数组which.min中最小的元素的索引.

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 = [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'

推荐答案

Numpy确实具有内置功能

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

这篇关于R在Python中等同于which()和which.min()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆