estebanpdl estebanpdl - 6 months ago 23
Python Question

Binomial classification using a list comprehension python

I'm working with

pandas
, and I want to add a new
Serie
with a binomial classification if a word is within a sentence.

For example:

year = [2010, 2011, 2012, 2011, 2012, 2010, 2011, 2012]
state = ['hello', 'my friend', 'hello and', 'coding', 'python', 'hello', 'who is', 'hello, friend']
data = {'year': Series(year), 'state': Series(state)}
pd = DataFrame(data)


So I tried this to get 1 or 0 if 'hello' is in item from state list.

data['hello'] = []
for item in data['state']:
if 'hello' in item:
data['hello'].append(1)
else:
data['hello'].append(0)


However, is there a method te get a binomial classification using a
list comprehension


Any suggestions will be appreciated! Thanks

Answer

A possible list comprehension equivalent is:

data['hello'] = [(1 if 'hello' in item else 0) for item in data['state']]

If True/False is acceptable:

data['hello'] = ['hello' in item for item in data['state']]
Comments