[英]Different operations for different columns in a numpy matrix?
我有一個0
和1
的平方numpy
矩陣,我必須根據該列執行不同的操作。
如果該列包含所有0
,則必須用1/number_of_the_colomns
替換這些0
(我使用命令matrix.shape[1]
),否則(如果colomn不包含所有0
),我必須將每個元素除以該列。
本質上,在執行這些操作之后,每個列的總和必須為1
。
我嘗試這樣做,但第三行出現錯誤: index returns 3-dim structure
a=numpy.nonzero(out_degree)
b=numpy.where(out_degree==0)
graph[:,b]=1/graph.shape[0]
graph[:,a]=graph/out_degree
graph
是numpy matrix
, out_degree
是一個vector
,其中包含sum
每個colomn的
我必須使用無循環的numpy
來節省時間。
一個開始將是:
import numpy as np
np.random.seed(1)
M, N = 5, 4
a = np.random.choice([0, 1, 2], size=(M, N), p=[0.6, 0.2, 0.2]).astype(float)
print(a)
a_inds = np.where(~a.any(axis=0))[0]
b_inds = np.setdiff1d(np.arange(N), a_inds, assume_unique=True)
b_col_sums = np.sum(a[:, b_inds], axis=0)
a[:, a_inds] = 1 / N
a[:, b_inds] /= b_col_sums
print(a)
輸出:
[[ 0. 1. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 1.]
[ 0. 2. 0. 1.]
[ 0. 0. 0. 0.]]
[[ 0.25 0.33333333 0.25 0. ]
[ 0.25 0. 0.25 0. ]
[ 0.25 0. 0.25 0.5 ]
[ 0.25 0.66666667 0.25 0.5 ]
[ 0.25 0. 0.25 0. ]]
這應該易於閱讀並且具有中等性能。 由於花式索引很多,它可能不是最快的。
它還不會檢查除以零的問題情況(這不是規范的一部分)!
編輯: OP只對正方形數組感興趣,因此以下內容將被忽略!
您聲明: In essence, after these operations the sum of each colomn must be 1.
然后執行以下操作: have to replace these 0 with 1/number_of_the_columns
,這是一個矛盾。 也許您需要在a[:, a_inds] = 1 / N
中用M替換N。
然后您獲得:
[[ 0.2 0.33333333 0.2 0. ]
[ 0.2 0. 0.2 0. ]
[ 0.2 0. 0.2 0.5 ]
[ 0.2 0.66666667 0.2 0.5 ]
[ 0.2 0. 0.2 0. ]]
您可以檢查非零元素,否則只需求和即可。
for col in range(a.shape[1]):
if np.any(a[:, col]):
a[:, col] /= np.sum(a[:, col])
else:
a[:, col] = 1/a.shape[1]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.