lundi 26 avril 2021

How Do I Create New Pandas Column Based On Word In A List

So I have a list and a dataframe. I want to take the the word from the list and make it the title of the column. if the word is the row its added to the newly created column. If its not in the row leave blank or NA. Should I use iloc?

import pandas as pd
wordlist = [['this is sentence 1'],['this is sentence 2'],['this is not a sentence'],['ok who is this']]
query=['is','not']
df = pd.DataFrame(wordlist, columns = ['Name'])

for word in query:
    if word in df['Name']:
        df[word] = word
df


Output

Name                       is     not  <<column titles
0   this is sentence 1     is     NA
1   this is sentence 2     is     NA
2   this is not a sentence is     not
3   ok who is this         is     NA

Aucun commentaire:

Enregistrer un commentaire