Home > Net >  Pandas - How to search for a value when dataframe contains lists?
Pandas - How to search for a value when dataframe contains lists?

Time:09-27

I am trying to search for a value in a dataframe of lists. For example if i search for dog it tells me its an animal. If i search for holden it tells me its a car. My dataframe looks like this:

     type                                  group
0  animal                       [cat, dog, bird]
1     car  [chevy, ford, nissan, holden, bently]

My code is to find what type a dog is:

import pandas as pd

data = {
  "type": ['animal', 'car'],
  "group": [['cat', 'dog', 'bird'], ['chevy', 'ford', 'nissan', 'holden', 'bently']]
}

df = pd.DataFrame(data)

find = ['dog']

df = df[pd.DataFrame(df['group'].tolist()).isin(find).any(1).values]
print('You detected: ', df['type'])

I get this output:

You detected:  0    animal
Name: type, dtype: object

But I am trying to get this output with type only

You detected: animal

If I change find = ['holden'] It returns:

You detected:  1    car
Name: type, dtype: object

I want this result You detected: car

Is this the best and simpliest way to search for a single value in my dataframe?

CodePudding user response:

You need .item() with column loc as well:

val = df.loc[pd.DataFrame(df['group'].tolist()).isin(find).any(1), 'type'].item()
print('You detected:', val)

Output:

You detected: animal
  • Related