user11669928
user11669928

Reputation:

Compare a list/array to a dataframe column?

I have a list or array contains values[apple,items] and i want a resultant df with where column('c') has the same list/array values.

Suppose in below eg: A can be a list/array/str and resultant df is based on the values in A compared with df 'c' column

eg:

   A = [apple,items]

df

                        a         b        c

                0       10        13      items

                1       9         12      testcase

                2       8         11      apple

                3       7         10      apple

                4       6         9       test

                5       5         8       items

Final df

                        a         b        c

                0       10        13      items

                1       8         11      apple

                2       7         10      apple

                3       5         8       items

I tried with boolean indexing but couldn't succeced

Upvotes: 0

Views: 5876

Answers (3)

You create a boolean:

selection = df['c'].isin(A)

and then get your final df from it:

Final_df = df[selection]

Upvotes: 1

rahlf23
rahlf23

Reputation: 9019

You want to use pd.Series.isin() and pass the results as a boolean mask to filter your original dataframe:

A = ['apples','items']

df_final = df[df['c'].isin(A)]

Upvotes: 1

Celius Stingher
Celius Stingher

Reputation: 18377

You should be able to work it out with this:

df['Status'] = df['c'].isin(A)

This should add a column named Status that will be True when the row for column C is apple or items, False otherwise.

Upvotes: 1

Related Questions