Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

One of the column in my df stores a list, and some of the raws have empty items in the list. For example:

[]

["X", "Y"]

[]

etc...

How can only take the raw whose list is not empty?

The following code does not work.

df[df["col"] != []] # ValueError: Lengths must match to compare

df[pd.notnull(df["col"])] # The code doesn't issue an error but the result includes an empty list

df[len(df["col"]) != 0] # KeyError: True

2 Answers

0 votes
by (25.1k points)

You can do it like this:

df[df["col"].str.len() != 0]

0 votes
by (1.3k points)

To extract all the data from a column containing an empty list, you can filter out rows in DataFrame by using lambda function.

import pandas as pd

sample_data={

‘col’:[ [ ], [ “X”, “Y”], [ ], [“Z] ]

}

df=pd.DataFrame(sample_data)

filtered_data= df[ df[‘col’ ].apply(lambda x: len(x)>0) ]

print(filtered_data)

This will filter out the empty list and output will be: 

    col

1 [X,Y]

3 [Z]

Related questions

0 votes
2 answers
asked May 30, 2019 in Python by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Sep 26, 2019 in Python by Sammy (47.6k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...