Home > database >  Set column based on another column np
Set column based on another column np

Time:04-27

I want to make sure column 2 is smaller than column 1 and where it is just set to 0

x = np.array([[0,1],[1,0]])
x = np.where((x[1] > (x[0])), 0, x)

print(x)=>[[0,0],[1,0]]

CodePudding user response:

Maybe this help you:

arr = np.array([[0,1],[1,0]])
arr[arr[:,1] > arr[:,0], 1] = 0
print(arr)

Output:

array([[0, 0],
       [1, 0]])

CodePudding user response:

You started with a list (of lists), so I'll give you a list answer.

First define a simple helper function:

def foo(row):
    if row[1]<row[0]:
        row[1] = 0
    return row

And apply it to x row by row:

In [37]: x = [[0,1],[1,0]]
In [38]: [foo(row) for row in x]
Out[38]: [[0, 1], [1, 0]]
  • Related