我需要找到一个独特的行numpy.array.
例如:
>>> a # I have
array([[1, 1, 1, 0, 0, 0],
[0, 1, 1, 1, 0, 0],
[0, 1, 1, 1, 0, 0],
[1, 1, 1, 0, 0, 0],
[1, 1, 1, 1, 1, 0]])
>>> new_a # I want to get to
array([[1, 1, 1, 0, 0, 0],
[0, 1, 1, 1, 0, 0],
[1, 1, 1, 1, 1, 0]])
Run Code Online (Sandbox Code Playgroud)
我知道我可以在阵列上创建一个集合并循环,但我正在寻找一个有效的纯numpy解决方案.我相信有一种方法可以将数据类型设置为void然后我可以使用numpy.unique,但我无法弄清楚如何使其工作.
有没有更好的方法来计算给定行在numpy 2D数组中出现的次数
def get_count(array_2d, row):
count = 0
# iterate over rows, compare
for r in array_2d[:,]:
if np.equal(r, row).all():
count += 1
return count
# let's make sure it works
array_2d = np.array([[1,2], [3,4]])
row = np.array([1,2])
count = get_count(array_2d, row)
assert(count == 1)
Run Code Online (Sandbox Code Playgroud) 我想通过给定的指标(x和y轴)修改空位图.对于指标给出的每个坐标,该值应该增加1.
到目前为止,一切似乎都很好.但如果我的指标数组中有一些类似的指标,它只会提高一次价值.
>>> img
array([[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]])
>>> inds
array([[0, 0],
[3, 4],
[3, 4]])
Run Code Online (Sandbox Code Playgroud)
操作:
>>> img[inds[:,1], inds[:,0]] += 1
Run Code Online (Sandbox Code Playgroud)
结果:
>>> img
array([[1, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 1, 0]])
Run Code Online (Sandbox Code Playgroud)
预期结果:
>>> img
array([[1, 0, 0, 0, 0],
[0, …Run Code Online (Sandbox Code Playgroud)