Python 中类似 R 语言的 which() 和 which.min() 函数的等价实现方法

36

我在这里阅读了类似主题的内容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'
6个回答

42

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

7
一个简单的循环就可以:
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)]

这里有一个实时示例

该示例是关于IT技术的,您可以点击链接查看。

1
所以除了循环之外没有其他方法吗?有内置函数吗? - Hadij
没有 Python 内置的方法,也许 NumPy 有相关的函数。 - Netwave

4

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

如果你有一个3x3的矩阵,你该怎么做呢?我喜欢你对R和Python的比较,这对于专业的R用户非常有用,但对像我这样的初学者Python用户也很有帮助。 - Henry Navarro

2
内置的index函数可以用于此目的:
x = [1,2,3,4,0,1,2,3,4,11] 
print(x.index(min(x)))
#4
print(x.index(max(x)))
#9

然而,对于基于条件的索引,np.where 或手动循环和 enumerate 可能会起到作用:

index_greater_than_two1 = [idx for idx, val in enumerate(x) if val>2]
print(index_greater_than_two1)
# [2, 3, 7, 8, 9]

# OR

index_greater_than_two2 = np.where(np.array(x)>2)
print(index_greater_than_two2)
# (array([2, 3, 7, 8, 9], dtype=int64),)

2

这是一种基于Python索引和Numpy的方法,它根据最小/最大值的索引返回所需列的值。

原始答案:Original Answer

df.iloc[np.argmin(df['column1'].values)]['column2']

谢谢。它适用于pandas.DataFrame。我的例子是一个简单的数组。 - Hadij

1
你也可以使用heapq来找到最小值的索引。然后你可以选择找到多个(例如前两个最小值的索引)。
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]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接