Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pandas - How to filter a dataframe that has a column containing a dictionary, using the existence of a key?

Having a dataframe that has a dictionary column

d = {'p1':[{'Apple':10},{'Ball': 20, 'Cat': 30}]}
df = pd.DataFrame(data=d)
    p1
0   {'Apple': 10}
1   {'Ball': 20, 'Cat': 30}

I would like to filter rows where the key 'Ball' exists.

    p1
1   {'Ball': 20, 'Cat': 30}
like image 251
Masaki Andou Avatar asked Oct 19 '25 03:10

Masaki Andou


1 Answers

Use boolean indexing with in statement:

df = df[df['p1'].map(lambda x: 'Ball' in x)]

print (df)

                        p1
1  {'Ball': 20, 'Cat': 30}
like image 133
jezrael Avatar answered Oct 21 '25 18:10

jezrael