[英]Group a numpy array
I have an one-dimensional array A
, such that 0 <= A[i] <= 11
, and I want to map A
to an array B
such that我有一个一维数组
A
,这样0 <= A[i] <= 11
,我想 map A
到数组B
这样
for i in range(len(A)):
if 0 <= A[i] <= 2: B[i] = 0
elif 3 <= A[i] <= 5: B[i] = 1
elif 6 <= A[i] <= 8: B[i] = 2
elif 9 <= A[i] <= 11: B[i] = 3
How can implement this efficiently in numpy
?如何在
numpy
中有效地实现这一点?
You need to use an int division by //3
, and that is the most performant solution您需要使用 int 除法
//3
,这是最高效的解决方案
A = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
B = A // 3
print(A) # [0 1 2 3 4 5 6 7 8 9 10 11]
print(B) # [0 0 0 1 1 1 2 2 2 3 3 3]
I would do something like dividing the values of the A[i] by 3 'cause you're sorting out them 3 by 3, 0-2 divided by 3 go answer 0, 3-5 go answer 1, 6-8 divided by 3 is equal to 2, and so on我会做一些事情,比如将 A[i] 的值除以 3,因为您将它们 3 除以 3、0-2 除以 3 go 答案 0、3-5 go 答案 1、6-8 除以3 等于 2,以此类推
I built a little schema here:我在这里建立了一个小架构:
A[i] --> 0-2.
divided by 3 = 0, what you wnat in array B[i] is 0, so it's ok A[i] --> 3-5.
除以 3 = 0,你在数组 B[i] 中的值是 0,所以没关系
A[i] --> 3-5.
divided by 3 = 1, and so on.除以 3 = 1,依此类推。 Just use a method to make floor the value, so that it don't become float type.
只需使用一种方法将 floor 设置为值,使其不会成为浮点类型。
Answers provided by others are valid, however I find this function from numpy quite elegant, plus it allows you to avoid for loop which could be quite inefficient for large arrays其他人提供的答案是有效的,但是我发现来自 numpy 的 function 非常优雅,而且它可以让您避免 for 循环,这对于大型 arrays
import numpy as np
bins = [3, 5, 8, 9, 11]
B = np.digitize(A, bins)
Something like this might work:像这样的东西可能会起作用:
C = np.zeros(12, dtype=np.int)
C[3:6] = 1
C[6:9] = 2
C[9:12] = 3
B = C[A]
If you hope to expand this to a more complex example you can define a function with all your conditions:如果您希望将此扩展为更复杂的示例,您可以使用所有条件定义 function:
def f(a):
if 0 <= a and a <= 2:
return 0
elif 3 <= a and a <= 5:
return 1
elif 6 <= a and a <= 8:
return 2
elif 9 <= a and a <= 11:
return 3
And call it on your array A
:并在您的数组
A
上调用它:
A = np.array([0,1,5,7,8,9,10,10, 11])
B = np.array(list(map(f, A))) # array([0, 0, 1, 2, 2, 3, 3, 3, 3])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.