How to drop row with bracket in Pandas

Viewed 41

I would like to drop the [] for a given df

df=pd.DataFrame(dict(a=[1,2,4,[],5]))

Such that the expected output will be

   a
0  1
1  2
2  4
3  5

Edit:

or to make thing more interesting, what if we have two columns and some of the cell is with [] to be dropped.

df=pd.DataFrame(dict(a=[1,2,4,[],5],b=[2,[],1,[],6]))
2 Answers

One way is to get the string repr and filter:

df = df[df['a'].map(repr)!='[]']

Output:

   a
0  1
1  2
2  4
4  5

For multiple columns, we could apply the above:

out = df[df.apply(lambda c: c.map(repr)).ne('[]').all(axis=1)]

Output:

   a  b
0  1  2
2  4  1
4  5  6

You can't use equality directly as pandas will try to align a Series and a list, but you can use isin:

df[~df['a'].isin([[]])]

output:

   a
0  1
1  2
2  4
4  5

To act on all columns:

df[~df.isin([[]]).any(1)]

output:

   a  b
0  1  2
2  4  1
4  5  6
Related