0

I am learning Python and this might be a noob question:

import pandas as pd

A = pd.DataFrame({"A":["house", "mouse", "car", "tree"]})

check_list = ["house", "tree"]

I want to check rowwise if the string in A is in check_list. The result should be

       A   YESorNO
0  house       YES
1  mouse        NO
2    car        NO
3   tree       YES
Pat
  • 1,299
  • 4
  • 17
  • 40
  • This is pretty much the same as this question: http://stackoverflow.com/questions/38499890/how-to-use-pandas-apply-function-on-all-columns-of-some-rows-of-data-frame and this: http://stackoverflow.com/questions/38501685/create-new-pandas-dataframe-column-based-on-if-else-condition-with-a-lookup – EdChum Jul 21 '16 at 12:50

2 Answers2

1

Use numpy.where with isin:

import pandas as pd
import numpy as np

A = pd.DataFrame({"A":["house", "mouse", "car", "tree"]})
check_list = ["house", "tree"]

A['YESorNO'] = np.where(A['A'].isin(check_list),'YES','NO')
print (A)
       A YESorNO
0  house     YES
1  mouse      NO
2    car      NO
3   tree     YES
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
1

If for some reason you don't want to import numpy,

import pandas as pd

A = pd.DataFrame({"A":["house", "mouse", "car", "tree"]})
check_list = ["house", "tree"]

Here's the one liner:

A['YESorNO'] = ['YES' if x in check_list else 'NO' for x in A['A']]
nico
  • 385
  • 4
  • 19