I have a data frame like this:
test = pd.DataFrame(columns=['A','B'])
test.loc[0,'A'] = 'a'
test.loc[0,'B'] = []
test.loc[1,'A'] = 'b'
test.loc[1,'B'] = ['a','b']
I want to get another data frame which contains the rows when column 'B' containing an empty list. What's the pythonic way of doing it?
A B
0 a []
Many thanks
As empty lists are going to be interpreted as collections to be processed in a vectorized way, I don't see any way to test it but to drill down to an apply
call:
test.B.apply(lambda c: c==[])
Out[71]:
0 True
1 False
Name: B, dtype: bool
test[test.B.apply(lambda c: c==[])]
Out[72]:
A B
0 a []
Empty lists translate to False as a boolean. Using ~
to convert that to True is a simple trick. It's easy to read and runs pretty fast for me. Definitely faster than using len()
.
test[~test['B'].astype(bool)]
A B
0 a []
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With