2

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]]

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...

2
  • 1
    Why do you fill with 0.3 and 0.8? Wouldn't it be 0.4 and 0.8 if they're aligned? Commented Dec 23, 2013 at 2:42
  • you are right, i edited the question Commented Dec 23, 2013 at 2:43

2 Answers 2

3

IIUC, how about:

>>> 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]])
Sign up to request clarification or add additional context in comments.

2 Comments

Because if you don't, a will have dtype=int. If you try to put a float into an int array, you won't get what you want.
@EmanuelePaolini: depends on the context. Here, where it seems that 0 was deliberately being used as a marker? Sure. In other cases, you'd want to use (abs(a) <= eps).all(axis=0) or something.
1

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:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.