Skip to content
Advertisement

How to filter a dataframe and each row, based on the presence of strings (from another list) in different columns and add a new column with annotation

I have a dataframe (df1) where I would like to search each row for items from listA. If the dataframe has a row that contains ‘positive’ and one or more of the items from listA, I would like to generate another dataframe (df2) by adding a column called result, listing the listA item + present. Items in list A, may exist as a stand alone item in each row of df1 or they may exist as part of a larger string. I’ve tried using pandas.DataFrame.loc but I am only able to search through one column at a time which isn’t ideal.

JavaScript

Output:

JavaScript

Advertisement

Answer

Updated:

I have created a function first which is applied to every row (‘axis=1’) and the results are added to the result column.

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement