Home > Mobile >  check if pandas series contains a dict
check if pandas series contains a dict

Time:07-09

I'd like to check if there is a cell with type dict in pandas series.

My pandas series looks something like this:

import pandas as pd
import numpy as np

s = pd.Series([{'a':'1'}, np.nan, {'b':'2'}, np.nan], name="s")

I'd like to basically check if there is at least 1 dict in the series and evaluate a condition.

if `dict` in series:
    print('True')
else:
    print('False')

CodePudding user response:

For a series:

>>> s = pd.Series([{'a':'1'}, np.nan, {'b':'2'}, np.nan], name="s")
>>> s.apply(type).eq(dict).any()
True

>>> s2 = pd.Series([['a', '1'], np.nan, ['b', '2'], np.nan], name="s2")
>>> s2.apply(type).eq(dict).any()
False

For a column of a DataFrame:

>>> df = pd.concat([s, s2], axis=1)
>>> df['s'].apply(type).eq(dict).any()
True

>>> df['s2'].apply(type).eq(dict).any()
False

>>> if s.apply(type).eq(dict).any():
...     print('True!')
...
True!

CodePudding user response:

No, it's not possible:

>>> s.explode().apply(type).eq(dict).groupby(level=0).max()
s    True
dtype: bool

>>> s.apply(lambda x: max(isinstance(i, dict) for i in x))
s    True
dtype: bool
  • Related