In python, determine the third element based on the first and second elements of the array.

Asked 2 years ago, Updated 2 years ago, 44 views

I have a two-dimensional list, and I would like to decide which element to put in the third based on the first element and the second element.

 li=np.array([-1,-2]
            [ 1,-2]
            [-1, 2]
            [ 1, 2]
             )

Specifically
(First element <0) and (Second element <0) then
1 for the third. (First element > 0) and (Second element < 0) and third element 2
(first element <0) and (second element >0) and third element 3
(First element > 0) and (Second element > 0) then the third element is
Add and

result=[-1,-2,1]
        [ 1,-2, 2]
        [-1, 2, 3]
        [ 1, 2, 4]]

It's like

I would like to do it by using the expressions and sequence operations (filter, map, where).

Thank you for your cooperation.

python python3

2022-09-30 21:29

2 Answers

How about this

>>import numpy as np
>>li=np.array([-1,-2],
...                [ 1, -2],
...                [-1,  2],
...                [ 1,  2]])
>>>n=li.shape [0]
>>li2=np.hstack([li,np.zeros(n,1)])
>>li2
array([-1.,-2.,0.],
       [ 1., -2.,  0.],
       [-1.,  2.,  0.],
       [ 1.,  2.,  0.]])
>>li2[np.where((li2[:,0]<0)&(li2[:,1]<0),2] = 1
<>>li2[np.where((li2[:,0]>0)&(li2[:,1]<0),2]=2
>>li2[np.where((li2[:,0]<0)&(li2[:,1]>0),2]=3
>>li2[np.where((li2[:,0]>0)&(li2[:,1]>0),2] = 4
>>li2
array([-1., -2., 1.],
       [ 1., -2.,  2.],
       [-1.,  2.,  3.],
       [ 1.,  2.,  4.]])


2022-09-30 21:29

I tried it just in case, but I think there's a better way.
Also, it's hard to read, so I prefer the one written in for honestly.

 li = [[-1,-2],
      [ 1,-2],
      [-1, 2],
      [ 1, 2]]

[i+[(1 if i[0]>0 else0)+(2 if i[1]>0 else0)+1] for i in li]

Output

[-1, -2, 1], [1, -2, 2], [-1, 2, 3], [1, 2, 4]]

add
It's a little shorter, so I'll add it.

 [i+[int(i[0]>0)+int(i[1]>0)*2+1] for i in li]

If you use numpy, you can also call it as follows.
It may be fast, but it's very hard to read.
If anyone knows a better way, please let me know.

import numpy as np
ni = np.array(li)

np.hstack(ni,np.sum(ni>0)*[1,2],1)[None].T+1)# Method 1
np.vstack(ni.T, np.sum(ni.T>0)*[[1], [2]], 0)+1)).T# Method 2


2022-09-30 21:29

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.