1
>>> x1 array([[ 0., -1., 2.], [ 3., -4., 2.], [ -2., 1., -8.]]) >>> x3 array([[ 0., -5., 2.], [ 3., 0., -3.], [ 3., 2., 8.]]) 

I need two matricies to be output: S and T, such that X is the sum of all positive values in X and Y, and T is the sum of all negative values in X and Y.

For example:

 S = array([ [ 0., 0., 4.], [ 6., 0., 2.], [ 3., 3., 8.]]) T = array([ [ 0., -6., 0.], [ 0., -4., -3.], [ -2., 0., -8.]]) 

I am using Python 2.6.7.

7
  • 2
    So you've tried anything? Atleast Googling the problem statement? Commented May 22, 2015 at 15:42
  • I tried to use nditer. but stuck operating on two indexes for two matrix while collecting them in two arrays Commented May 22, 2015 at 15:45
  • If you have tried something then please edit your question and add the details Commented May 22, 2015 at 15:46
  • @YXD , you are correct, I made a mistake in preparing the output -- I have fixed it Commented May 22, 2015 at 15:47
  • What happens if there is a positive and a negative number when you perform your calcuation? For example, what would be the output in posArray and negArray if S[0][2] were -2? Commented May 22, 2015 at 15:48

2 Answers 2

3

You can use np.clip() to selectively add

In [140]: x1.clip(min=0) + x3.clip(min=0) Out[140]: array([[ 0., 0., 4.], [ 6., 0., 2.], [ 3., 3., 8.]]) In [141]: x1.clip(max=0) + x3.clip(max=0) Out[141]: array([[ 0., -6., 0.], [ 0., -4., -3.], [-2., 0., -8.]]) 
Sign up to request clarification or add additional context in comments.

Comments

1

As well as clip you can do this by multiplying by boolean arrays:

>>> x1 * (x1 > 0) + x3 * (x3 > 0) array([[ 0., -0., 4.], [ 6., 0., 2.], [ 3., 3., 8.]]) >>> x1 * (x1 <= 0) + x3 * (x3 <= 0) array([[ 0., -6., 0.], [ 0., -4., -3.], [-2., 0., -8.]]) >>> 

6 Comments

which way will be better? I like you way since by looking at it makes sense but I have decent size (2k x 1k) matrix and I do this 100K times
Probably clip is better. But maybe you could post a question about your broader problem. Sometimes you can avoid the issue altogether...
Thank you, there is no broader problem.. this is the problem. we are using 3rd party lib that requires matrix in this format, we have about 100k matrix that we need to pass split way and 3rd party will do the magic -- black box-- Thank you for your answer and explanation.
@XYD, since I move forward, I realized that the matrix size I have is not same for all matrix, meaning I have one matrix (S) of shape(8,5) and another of (T) shape(2,9) .. i need to have new matrix shape (8,9) -- I tried zeros() but didn't get the results I needed. any suggestion ?
@Sendi_t best thing is to post a new question on this and show an example of expected inputs and output
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.