如何检查元素在熊猫中是否为空列表?

时间:2019-07-05 13:21:38

标签: python pandas

我df中的一列存储了一个列表,而某些raws列表中有空项目。例如:

  

[]

     

[“ X”,“ Y”]

     

[]

等...

如何只能获取列表不为空的原始文件?

以下代码不起作用。

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

5 个答案:

答案 0 :(得分:4)

尝试一下:

df[df['col'].apply(len).gt(0)]

答案 1 :(得分:3)

您可以这样做:

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

示例:

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]

答案 2 :(得分:3)

这可能是最有效的解决方案。

df[df["col"].astype(bool)]

答案 3 :(得分:1)

bool

布尔上下文中的空列表为False。空列表就是我们所说的虚假信息。程序员很容易知道哪些对象是假的和真实的。

您还可以对具有布尔列表(不仅仅是布尔序列)的数据框进行切片。因此,我将使用一种理解方法来加快检查速度。

df[[bool(x) for x in df.col]]

或者字符更少

df[[*map(bool, df.col)]]

答案 4 :(得分:0)

您可以使用str.len()检查列表是否为空,然后取反:

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

str.len用于返回对象长度的Python内置函数。

您的输出应该是预期的。

相关问题