2
Dateframe df:A  B  C  D        E
             1  2  4  6        #Value to be updated for this column  
             12 34 5  54
             4  8  12 4
             3  5  6  2
             5  7  11 27
numpy ndarray(shape(4*1)):
         npar=  ([12]
           [6]
           [2]
           [27]
          )

I have above dataframe df and array npar, I want to compare value of column D in array npar. if value of column D is found in array npar anywhere . I want to update column E with 1 else 0 for that row of dataframe df. Kindly suggest how I can do this with sample code.

1
  • df['E'] = df.D.isin(npar).astype(int) Commented Apr 27, 2018 at 7:17

1 Answer 1

1

You need isin, but first is necessery flatten array by numpy.ravel and last convert boolean mask to integers - Trues are 1s and Falses are 0s:

df['E'] = df.D.isin(npar.ravel()).astype(int)
print (df)
    A   B   C   D  E
0   1   2   4   6  1
1  12  34   5  54  0
2   4   8  12   4  0
3   3   5   6   2  1
4   5   7  11  27  1

Detail:

npar = np.array([[12],[6],[2],[27]])
print (npar)
[[12]
 [ 6]
 [ 2]
 [27]]

print (npar.ravel())
[12  6  2 27]

print (df.D.isin(npar.ravel()))
0     True
1    False
2    False
3     True
4     True
Name: D, dtype: bool
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot it worked. npar.ravel() is the key here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.