我有一个像这样的numpy数组
[[ 0, 57],
[ 7, 72],
[ 2, 51],
[ 8, 67],
[ 4, 42]]
我想为每一行找出第二列中有多少个元素在该行第二列值的特定距离内(例如10)。因此,在此示例中,解决方案将是
[[ 0, 57, 3],
[ 7, 72, 2],
[ 2, 51, 3],
[ 8, 67, 3],
[ 4, 42, 2]]
因此[第一行,第三列]为3,因为第二列(57,51,67)中有3个元素,它们与57之间的距离为10。
任何帮助将不胜感激!
答案 0 :(得分:2)
这是将broadcasting
与(np.abs(a[:,1,None] - a[:,1]) <= 10).sum(1)
结合使用的一种方法-
outer subtract builtin
使用count_nonzero
和np.count_nonzero(np.abs(np.subtract.outer(a[:,1],a[:,1]))<=10,axis=1)
进行计数-
# Input array
In [23]: a
Out[23]:
array([[ 0, 57],
[ 7, 72],
[ 2, 51],
[ 8, 67],
[ 4, 42]])
# Get count
In [24]: count = (np.abs(a[:,1,None] - a[:,1]) <= 10).sum(1)
In [25]: count
Out[25]: array([3, 2, 3, 3, 2])
# Stack with input
In [26]: np.c_[a,count]
Out[26]:
array([[ 0, 57, 3],
[ 7, 72, 2],
[ 2, 51, 3],
[ 8, 67, 3],
[ 4, 42, 2]])
样品运行-
In [53]: from scipy.spatial.distance import cdist
In [54]: (cdist(a[:,None,1],a[:,1,None], 'minkowski', p=2)<=10).sum(1)
Out[54]: array([3, 2, 3, 3, 2])
或者用SciPy's cdist
-
n = len(a)
count = np.empty(n, dtype=int)
for i in range(n):
count[i] = np.count_nonzero(np.abs(a[:,1]-a[i,1])<=10)
对于输入的一百万行,我们可能想求助于循环--
dic_courses = {'C1': 10, 'C2': 5, 'C3': 20}
dic_rooms = {'R1': 5, 'R2': 10, 'R3': 20}
d = {}
for k1, v1 in dic_courses.items():
for k2, v2 in dic_rooms.items():
d.update({(k1, k2): abs(v1 - v2)})
print(d)
# {('C1', 'R1'): 5, ('C1', 'R2'): 0, ('C1', 'R3'): 10,
# ('C2', 'R1'): 0, ('C2', 'R2'): 5, ('C2', 'R3'): 15,
# ('C3', 'R1'): 15, ('C3', 'R2'): 10, ('C3', 'R3'): 0}
答案 1 :(得分:1)
这是一种非广播方法,它利用以下事实:要知道10个数字中有3个数字,可以从严格小于7的数字中减去<= 13个数字。
import numpy as np
def broadcast(x, width):
# for comparison
return (np.abs(x[:,None] - x) <= width).sum(1)
def largest_leq(arr, x, allow_equal=True):
maybe = np.searchsorted(arr, x)
maybe = maybe.clip(0, len(arr) - 1)
above = arr[maybe] > x if allow_equal else arr[maybe] >= x
maybe[above] -= 1
return maybe
def faster(x, width):
uniq, inv, counts = np.unique(x, return_counts=True, return_inverse=True)
counts = counts.cumsum()
low_bounds = uniq - width
low_ix = largest_leq(uniq, low_bounds, allow_equal=False)
low_counts = counts[low_ix]
low_counts[low_ix < 0] = 0
high_bounds = uniq + width
high_counts = counts[largest_leq(uniq, high_bounds)]
delta = high_counts - low_counts
out = delta[inv]
return out
这通过了我的测试:
for width in range(1, 10):
for window in range(5):
for trial in range(10):
x = np.random.randint(0, 10, width)
b = broadcast(x, window).tolist()
f = faster(x, window).tolist()
assert b == f
并且即使在较大尺寸下也表现良好:
In [171]: x = np.random.random(10**6)
In [172]: %time faster(x, 0)
Wall time: 386 ms
Out[172]: array([1, 1, 1, ..., 1, 1, 1], dtype=int64)
In [173]: %time faster(x, 1)
Wall time: 372 ms
Out[173]: array([1000000, 1000000, 1000000, ..., 1000000, 1000000, 1000000], dtype=int64)
In [174]: x = np.random.randint(0, 10, 10**6)
In [175]: %timeit faster(x, 3)
10 loops, best of 3: 83 ms per loop