对于此矩阵K =
[[-1. 1. 0.]
[ 0. 0. 0.]
[ 0. -1. 1.]
[ 0. 0. 0.]
[ 0. -1. 1.]
[ 0. 0. 0.]]
任务是在数组中存储非零唯一行的索引(此处答案为{0,2}),以便
K([0,2],:)
可用于线性代数运算。 我的尝试是:
myList = []
for i in range(len(K)): #generate pairs
for j in range(i+1,len(K)): #travel down each other rows
if np.array_equal(K[i],K[j]) and np.any(K[i] != 0, axis=1) and np.any(K[j] != 0, axis=1):
myList.append(K[i])
print ('indices of similar-non-zeros rows are\n',(i, j)),
elif not np.array_equal(K[i],K[j]) and np.any(K[i] != 0,axis=1) and np.any(K[j] != 0, axis=1):
myList.append(K[i])
print ('indices of non-similar-non-zeros rows are\n',(i, j)),
else:
continue
new_K = np.asmatrix(np.asarray(myList))
new_new_K = np.unique(new_K,axis=0)
print('Now K is \n',new_new_K)
答案是:
new_new_K = [[-1. 1. 0.]
[ 0. -1. 1.]]
问题1:如何以pythonic方式进行。以上是具有矩阵存储限制的替代解决方案,但更优选地将索引存储在阵列中。
答案 0 :(得分:2)
您可以使用简单的rating_position_recalculate_service:
class: App\Service\RatingPositionRecalculateService
autowire: false
arguments:
$entityManager: '@doctrine.orm.entity_manager'
$producer: '@old_sound_rabbit_mq.rating_position_producer'
循环for
来实现此目的。
enumerate
<强>结果
import numpy as np
A = np.array([[-1, 1, 0],
[ 0, 0, 0],
[ 0, -1, 1],
[ 0, 0, 0],
[ 0, -1, 1],
[ 0, 0, 0]])
seen = {(0, 0, 0)}
res = []
for idx, row in enumerate(map(tuple, A)):
if row not in seen:
res.append(idx)
seen.add(row)
示例#2
print(A[res])
[[-1 1 0]
[ 0 -1 1]]
答案 1 :(得分:2)
您可以使用np.unique
及其axis
参数来获取起始唯一行索引,然后过滤掉其对应行为全零的唯一一行索引,如下所示 -
def unq_row_indices_wozeros(a):
# Get unique rows and their first occuring indices
unq, idx = np.unique(a, axis=0, return_index=1)
# Filter out the index, the corresponding row of which is ALL 0s
return idx[(unq!=0).any(1)]
示例运行 -
In [53]: # Setup input array with few all zero rows and duplicates
...: np.random.seed(0)
...: a = np.random.randint(0,9,(10,3))
...: a[[2,5,7]] = 0
...: a[4] = a[1]
...: a[8] = a[3]
In [54]: a
Out[54]:
array([[5, 0, 3],
[3, 7, 3],
[0, 0, 0],
[7, 6, 8],
[3, 7, 3],
[0, 0, 0],
[1, 5, 8],
[0, 0, 0],
[7, 6, 8],
[2, 3, 8]])
In [55]: unq_row_indices_wozeros(a)
Out[55]: array([6, 9, 1, 0, 3])
# Sort those indices if needed
In [56]: np.sort(unq_row_indices_wozeros(a))
Out[56]: array([0, 1, 3, 6, 9])