Python Forum
Thread Rating:
  • 1 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
array coding problem
#1
Hi everyone

I have a 3d numpy array called p as follows

array([[[0, 1, 2],
        [3, 4, 5],
        [6, 7, 8]],

       [[0, 1, 2],
        [3, 4, 5],
        [6, 7, 8]],

       [[0, 1, 2],
        [3, 4, 5],
        [6, 7, 8]]])
I also have a 2d numpy array called q as follows

[[0, 2, 1],
[3, 7, 5],
[9, 7, 6]],

What I want to achieve is to "gate" p with q. In other words for any position in axis 0 in p I want a comparison to be made with the corresponding position in 1. if the corresponding value in is greater than p, I want to replace the value in p with the number 130.

The correct answer should be a 3d numpy array as follows

array([[[0, 130, 2],
[3, 130, 5],
[130, 7, 8]],

[[0, 130, 2],
[3, 130, 5],
[130, 7, 8]],

[[0, 130, 2],
[3, 130, 5],
[130, 7, 8]]])

So first the values at p[0][0][0] and p[1][0][0] and p[2][0][0] are all compared with the value at q[0][0]. If the value in p is less than the value in q the value in p is substituted with 130.

So first the values at p[0][1][2] and p[1][1][2] and p[1][1][2] are all compared with the value at q[1][2]. If the value in p is less than the value in q the value in p is substituted with 130.

I have tried to code this as follows

p

array([[[0, 1, 2],
[3, 4, 5],
[6, 7, 8]],

[[0, 1, 2],
[3, 4, 5],
[6, 7, 8]],

[[0, 1, 2],
[3, 4, 5],
[6, 7, 8]]])

q

array [[0, 2, 1],
[3, 7, 5],
[9, 7, 6]],

j=np.where(q[:]>p[:],p,130]

SyntaxError: invalid syntax

How can I use np.where to substitute the value 130 along each axis 0 position in P with teh corresponding position in q?

Thanks Peter
Reply
#2
>>> for idx,x in np.ndenumerate(p):
...    if (p[idx] < q[idx[1],idx[2]] ):
...      p[idx]=130
...
>>> p
array([[[  0, 130,   2],
        [  3, 130,   5],
        [130,   7,   8]],

       [[  0, 130,   2],
        [  3, 130,   5],
        [130,   7,   8]],

       [[  0, 130,   2],
        [  3, 130,   5],
        [130,   7,   8]]])
Reply
#3
Thanks

I note that you have used a FOR loop. I am trying to vectorise my code to keep it fast. Is there a vectorised solution? This code runs very slowly.

cheers Peter
Reply
#4
I tried with below and got same result as previous one:

p=np.array([[[0, 1, 2],
[3, 4, 5],
[6, 7, 8]],

[[0, 1, 2],
[3, 4, 5],
[6, 7, 8]],

[[0, 1, 2],
[3, 4, 5],
[6, 7, 8]]])

q=np.array([[0, 2, 1],
[3, 7, 5],
[9, 7, 6]])

Below statement i used to update the value
p[p<q]=130

result:
array([[[ 0, 130, 2],
[ 3, 130, 5],
[130, 7, 8]],

[[ 0, 130, 2],
[ 3, 130, 5],
[130, 7, 8]],

[[ 0, 130, 2],
[ 3, 130, 5],
[130, 7, 8]]])

Hope this will help.....
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Access 2D array problem landlord1984 1 3,291 Jan-23-2017, 08:33 AM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020