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

问题描述 投票:10回答:5

我读了类似的话题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中最小的元素的indeces。

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 which
5个回答
17
投票

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
投票

一个简单的循环将:

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


1
投票

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


1
投票

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

1
投票

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

df.iloc[np.argmin(df['column1'].values)]['column2']
© www.soinside.com 2019 - 2024. All rights reserved.