2
$\begingroup$

Here's what my data frame look like:

Number  Age      Famous_for                            
1       35       "businessman chairman of IBM (1973–1981)"
2       42       "musician (House of Freaks Gutterball)"
3       87       "baseball player (Oakland Athletics)"

I want to create additional column that will contain a dummy variable whether or not person was involved with entertaining business. Something like that:

Number..Age..................Famous_for.....................Entertaining                            
1.......35.......businessman chairman of IBM (1973–1981)........0              
2.......42.......musician (House of Freaks Gutterball)..........1                
3.......87.......baseball player (Oakland Athletics)............0       

How do I create a column based on the certain words in the famous for column (such as "musician", "club", "actor" and etc)? I tried the following:

df['entertaining'] = np.where(df['famous_for']>="musician", 1, 0)

but it wouldn't work. How can I do this in Python?

$\endgroup$
1
$\begingroup$

You can use str.contains on the DataFrame:

df = pd.DataFrame({'Age' : pd.Series([35,42,87], index=[1,2,3]),
        'Famous_for': pd.Series(['businessman chairman of IBM (1973–1981)',
                                 'musician (House of Freaks Gutterball)',
                                 'baseball player (Oakland Athletics)'], 
        index=[1,2,3])
        })

df['entertaining'] = df['Famous_for'].str.contains('musician')
print (df)

   Age                               Famous_for entertaining
1   35  businessman chairman of IBM (1973–1981)        False
2   42    musician (House of Freaks Gutterball)         True
3   87      baseball player (Oakland Athletics)        False

Note that str.contains also accepts a regular expression, so if you wish to search for various words you might use

df['entertaining'] = df['Famous_for'].str.contains('musician|businessman')
$\endgroup$
1
  • $\begingroup$ I'd do it this way: words = ['musician','club','actor']; df['entertaining'] = df['Famous_for'].str.lower().str.contains('|'.join(words)).astype(np.int8) $\endgroup$
    – MaxU
    Jan 7 '17 at 23:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.