How to check if a Pandas row contains an empty set
10,395
Solution 1
One way:
df2.apply(lambda x: any(x.values == {}), axis=1)
Output:
0 False
1 True
dtype: bool
OR
df2['c'] = np.max(df2.values == {}, 1).astype(bool)
Output:
col1 col2 c
0 1 3 False
1 2 {} True
Solution 2
You can take advantage of the fact that len({})=0 and apply a lambda function:
df2['col2'].apply(lambda x: len(x)==0)
Note that this will return True for empty lists and dicts as well.
Solution 3
You can just compare df2.values
to an empty dictionary:
In [ ]: df2['col_2_contains_empty_set'] = (df2.values == {}).any(axis=1)
...: df2
Out[ ]:
col1 col2 col_2_contains_empty_set
0 1 3 False
1 2 {} True
Author by
Zubo
Updated on August 03, 2022Comments
-
Zubo almost 2 years
I want to check if a Pandas Dataframe row contains an empty set in a specific column, i.e.
d = {'col1': [1, 2], 'col2': [3, {}]} df2 = pd.DataFrame(data=d) col1 col2 0 1 3 1 2 {}
and then
df2['col_2_contains_empty_set'] = ? # how to implement this
should give
col1 col2 col_2_contains_empty_set 0 1 3 False 1 2 {} True
What's the correct way to do this? Can't do
bool(df['col2'])
or
df['col2'].bool()
as
Series
are have ambiguous Boolean values, I think.