2

I have a matrix as shown:

X = 
    t   r   v
a   4   7   3
b   0   1   8
c   0   7   9
d   9   6   0
e   1   3   4
f   8   7   2
g   5   7   4
h   5   1   0
i   9   8   6
j   4   6   7

I have a dictionary with key value pair as follows:

Y = {'t': 5, 'r': 4, 'v': 2}

I am trying to map the values of Y with each column of the matrix X such that if the value in Y is greater than or equal to the value in X, we get '1' else we get '0'.

For ex: In the above code, the output should be:

Z = [011,001,011,110,001,111,111,100,111,011]

In this, for the first row, 't'=4 < 't'=5 in X; 'r'=7 > 'r'=4; 'v'=3 > 'v'=2 and so we get 011, and so on. I went through this and this but couldn't get a solution that I am looking for. TIA.

Daksh Agarwal
  • 167
  • 2
  • 12

2 Answers2

1

Use ge with cast mask to integers by astype:

df = df.ge(Y).astype(int)
print (df)
   t  r  v
a  0  1  1
b  0  0  1
c  0  1  1
d  1  1  0
e  0  0  1
f  1  1  1
g  1  1  1
h  1  0  0
i  1  1  1
j  0  1  1

If want output list first convert to str and then join each row:

L = df.ge(Y).astype(int).astype(str).apply(''.join, axis=1).tolist()
print (L)
['011', '001', '011', '110', '001', '111', '111', '100', '111', '011']

Or new column Z:

df['Z'] = df.ge(Y).astype(int).astype(str).apply(''.join, axis=1)
print (df)
   t  r  v    Z
a  4  7  3  011
b  0  1  8  001
c  0  7  9  011
d  9  6  0  110
e  1  3  4  001
f  8  7  2  111
g  5  7  4  111
h  5  1  0  100
i  9  8  6  111
j  4  6  7  011

Detail:

print (df.ge(Y))
       t      r      v
a  False   True   True
b  False  False   True
c  False   True   True
d   True   True  False
e  False  False   True
f   True   True   True
g   True   True   True
h   True  False  False
i   True   True   True
j  False   True   True
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
1

Use zip and column extraction in pandas as

keys = ["t", "r", "v"]

ans = zip(*[np.array(X[key] >= y[key]) for key in keys])

This will give you the required output but the data type will be bool which can be converted to int

layog
  • 4,661
  • 1
  • 28
  • 30