gpt4 book ai didi

python - R 的 which() 和 which.min() 在 Python 中等价

转载 作者:太空狗 更新时间:2023-10-29 17:56:06 26 4
gpt4 key购买 nike

我读了类似的话题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'

最佳答案

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

关于python - R 的 which() 和 which.min() 在 Python 中等价,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48519062/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com