How can I create a new column in a pandas dataframe by following these conditions?
if column 'Ex' match with one of the elements in this list l=['cnn', 'nba', 'agi', 'apple'] then:
Create a new column, S, having value 1 for those elements in the list above.
For example:
Original dataframe:
Ex
cnn
dog
mine
agi
Output expected:
Ex S
cnn 1
dog 0
mine 0
agi 1
I would approach the problem as follows:
df['S']=df['Ex'].apply(lambda x: any([k in x for k in l]))
to check if a row matches (I do not want a 'contains' condition) one of the value within l. I do not know how to assign values 1 or 0, but I think adding an if statement.
You can just do isin
df['S']=df['Ex'].isin(l).astype(int)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With