Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select rows that based on a where statement

How can I select values that have the word "link" in them and make them in category1 and "popcorn" in them to make them category2 and all else put in category3?

Here is a sample but my actual dataset has hundreds of rows

data = {'model': [['Lisa', 'link'], ['Lisa 2', 'popcorn'], ['telephone', 'rabbit']],
        'launched': [1983, 1984, 1991]}

df = pd.DataFrame(data, columns = ['model', 'launched'])

Desired

 Model                 launched         category
 ['Lisa', 'link']        1983             1
 ['Lisa 2', 'popcorn']   1984             2
 ['telephone', 'rabbit'] 1991             3
like image 391
OptimusPrime Avatar asked Mar 18 '26 06:03

OptimusPrime


1 Answers

You could use np.select to set category to 1 or 2 depending on whether 'link' or 'popcorn' is contained in a given list. Set default to 3 for the case where neither of them are contained:

import numpy as np
c1 = ['link' in i for i in df.model]
c2 = ['popcorn' in i for i in df.model]
df['category'] = np.select([c1,c2], [1,2], 3)

              model       launched  category
0         [Lisa, link]      1983         1
1    [Lisa 2, popcorn]      1984         2
2  [telephone, rabbit]      1991         3
like image 118
yatu Avatar answered Mar 20 '26 20:03

yatu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!