Remove rows with empty lists from pandas data frame
To avoid converting to str
and actually use the list
s, you can do this:
df[df['donation_orgs'].map(lambda d: len(d)) > 0]
It maps the donation_orgs
column to the length of the lists of each row and keeps only the ones that have at least one element, filtering out empty lists.
It returns
Out[1]:
donation_context donation_orgs
1 [In lieu of flowers , memorial donations] [the research of Dr.]
as expected.
You could try slicing as though the data frame were strings instead of lists:
import pandas as pd
df = pd.DataFrame({
'donation_orgs' : [[], ['the research of Dr.']],
'donation_context': [[], ['In lieu of flowers , memorial donations']]})
df[df.astype(str)['donation_orgs'] != '[]']
Out[9]:
donation_context donation_orgs
1 [In lieu of flowers , memorial donations] [the research of Dr.]