简体   繁体   English

用numpy数组中的值替换“零列”

[英]Replace “zero-columns” with values from a numpy array

Ok it´s late and i cannot solve the easiest problems anymore: 好的,已经晚了,我不能再解决最简单的问题了:

I have a Matrix with "zero-columns", these columns should be replaced with 我有一个带有“零列”的矩阵,这些列应替换为

a value from another array (same column index) that has the same number of columns: 来自另一个具有相同列数的数组(相同列索引)的值:

a=np.array([[2,0,0,0],[1,0,2,0],[1,0,5,0]])
b=np.array([0.3,0.4,0.6,0.8])

result should be: 结果应该是:

c=np.array([[2,0.4,0,0.8],[1,0.4,2,0.8],[1,0.4,5,0.8]])

i tried: 我试过了:

#searches for an entire zero-column indexes
wildcard_cols = np.nonzero(a.sum(axis=0) == 0)

i get: 我得到:

out: wildcard_cols=array([[1, 3]], dtype=int64)# that is right

then i wanted to get a list from this output to iterate over the items in a list 然后我想从此输出中获取列表以遍历列表中的项目

wildcard_cols=np.asarray(wildcard_cols)
wildcard_cols=wildcard_cols.tolist()    

but i get a list in a list(?) out=[[1, 3]] 但是我得到列表中的列表(?)out = [[1,3]]

so i cannot do: 所以我做不到:

for item in wildcard_cols:
    a[:,item]=b[item]
    #this does not work because i want to change every value in the column

i maybe thinking to complicated, but maybe someone finds a quick solution... 我可能想变得复杂,但也许有人找到了快速解决方案...

IIUC, how about: IIUC,如何:

>>> a = np.array([[2,0,0,0],[1,0,2,0],[1,0,5,0]])*1.0
>>> b = np.array([0.3,0.4,0.6,0.8])
>>> wild = (a == 0).all(axis=0)
>>> c = a.copy()
>>> c[:,wild] = b[wild]
>>> c
array([[ 2. ,  0.4,  0. ,  0.8],
       [ 1. ,  0.4,  2. ,  0.8],
       [ 1. ,  0.4,  5. ,  0.8]])

a little shorter and works with higher dimensional arrays as long as they are broadcast-able 只要可以广播,就短一点,并可以使用高维数组

np.where((a == 0.).all(axis=0), b, a)

unfortunately as of numpy 1.8 its slower than direct indexing like DSM proposed, a more general variant of that would be: 不幸的是,从numpy 1.8开始,它比DSM建议的直接索引要慢,它的更一般的变化是:

wild = (a == 0).all(axis=0)
c = a.copy()
c[(slice(None),) + np.nonzero(wild)] = b[wild]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM