There is a table:

df = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo", ... "bar", "bar", "bar", "bar"], ... "B": ["one", "one", "one", "two", "two", ... "one", "one", "two", "two"], ... "C": ["2017", "2017", "2018", "2017", ... "2018", "2017", "2018", "2017", ... "2017"], ... "D": [1, 2, 2, 3, 3, 4, 5, 6, 7]}) 

It is necessary to put down in the E column the values ​​'Yes' if in the row A 'foo' and 'No' if 'bar'

I try to iterate over the column as follows:

 for x in df['A']: if 'foo' in x: df'['E'] = 'Yes' 

But in this form, as I understand it, one value will be put on the entire column 'E'. How to do it right?

That is, you need not just when the value matches, but when a certain object enters the string, you must fulfill the condition

    1 answer 1

    Use the Series.map (...) method:

     In [178]: df['E'] = df['A'].map({'foo':'Yes','bar':'No'}) 

    To check by substring:

     In [183]: df['E'] = np.where(df['A'].str.contains('fo'), 'Yes', 'No') 

    Result:

     In [184]: df Out[184]: ABCDE 0 foo one 2017 1 Yes 1 foo one 2017 2 Yes 2 foo one 2018 2 Yes 3 foo two 2017 3 Yes 4 foo two 2018 3 Yes 5 bar one 2017 4 No 6 bar one 2018 5 No 7 bar two 2017 6 No 8 bar two 2017 7 No 
    • And if it is not 'foo', but 'fo', that is, you need to determine the entry in the string. - Gremlin
    • Thank. That helped. And if you do without numpy. For example, I know only x value without y, or a complex condition with several if. how to iterate in this case and check the condition - Gremlin
    • @Gremlin, better ask a new question with a specific example and it is advisable to give an example of various complex options that may occur in your real data. The answer can vary greatly depending on what you want to get at the output - MaxU