How to check if an element is an empty list in pandas?
You can do this:
df[df["col"].str.len() != 0]
Example:
import pandas as pd
df = pd.DataFrame({"col": [[1], [2, 3], [], [4, 5, 6], []]}, dtype=object)
print(df[df["col"].str.len() != 0])
# col
# 0 [1]
# 1 [2, 3]
# 3 [4, 5, 6]
Try this:
df[df['col'].apply(len).gt(0)]
This is probably the most efficient solution.
df[df["col"].astype(bool)]
bool
An empty list in a boolean context is False
. An empty list is what we call falsey. It does a programmer well to know what objects are falsey and truthy.
You can also slice a dataframe with a boolean list (not just a boolean series). And so, I'll use a comprehension to speed up the checking.
df[[bool(x) for x in df.col]]
Or with even less characters
df[[*map(bool, df.col)]]