list of strings as columns names in a dataframe and checking occurence

Viewed 224

I have this dataframe with one column Strings:

   Strings            
["string1"]
["string2","string3"]
["string4"]

I want to use a list as new columns name in this df and the value of the row set to 1 if the column name is in the Strings column.

list_name = ['string10', 'string1', string2']


Strings                string1    string2    string10
["string1"]                1         0           0
["string2","string3"]      0         1           0
["string4"]                0         0           0

How can I do this?

1 Answers

You may need to convert the list of strings to a string of each element for this to work. See example below using np.where and the str.contains methods:

import numpy as np
stringsCheck = [f'string{i}' for i in range(1,10)]
someDf = pd.DataFrame({'Strings': ["string1", "string2, string3", "string4"] })
for i in stringsCheck:
    someDf[f'{i}'] = np.where(someDf.Strings.str.contains(f'{i}'), 1, 0)

Output:

someDf.iloc[:,: 5]
Out[116]: 
            Strings  string1  string2  string3  string4
0           string1        1        0        0        0
1  string2, string3        0        1        1        0
2           string4        0        0        0        1
Related