4

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

2
  • If you don't have empty strings, you can use test[test['B'].str.len()==0] Commented Feb 9, 2017 at 17:33
  • Yes, it seems to work, I tried len() in different position and didn't work out for me. Thanks! Commented Feb 10, 2017 at 10:04

2 Answers 2

5

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  []
Sign up to request clarification or add additional context in comments.

Comments

2

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  []

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.