Home > Mobile >  Extract rows Pandas If the value of column is contained in another column
Extract rows Pandas If the value of column is contained in another column

Time:07-26

I have the following dataset (see figure) dataframe

I need to extract all rows from the Results data frame such that Results['Class'] is in Results[Path_x']

(In the specific case, it should only return me the second-to-last line because Results['Class'] is totally contained in Results['Path_x'] in the penultimate case)

I tried the following line of code:

results=results[results['Class'].isin(results['Path_x'])]

However, that line always generates an empty data frame.

CodePudding user response:

You can do

mask = results.apply(lambda x: ['Class'] in results['Path_x'], axis=1)
results= results.loc[mask, :]

See this question: Python Pandas: Check if string in one column is contained in string of another column in the same row

  • Related