从数据框中删除示例 pandas python

delete an example from dataframe pandas python

我有一个这样的数据框

     Phrase                          Sentiment

   [ good , movie ]                   positive

   [wooow ,is , it ,very, good  ]   positive

      []                             negative
      []                              pOSTIVE

列Phrase类型为object,需要删除包含[]的行 我不知道如何使用 python

像这样:

 Phrase                          Sentiment

   [ good , movie ]                   positive

   [wooow ,is , it ,very, good  ]   positive

您可以通过 str.len()==0 检查是否存在空列表,并根据此通过执行否定操作过滤 DF

df[df.Phrase.str.len() != 0]

要知道存在空列表的行:

df.Phrase.str.len() == 0

0    False
1    False
2     True
3     True
Name: Phrase, dtype: bool

万一存在空字符串,它们的长度也等于零。在这种情况下,通过在 map.

上使用自定义函数,可以根据类型进行过滤。
df[df.Phrase.map(lambda x: len(x) if isinstance(x, list) else None) != 0]

如果它们是列表的字符串表示,那么您可以直接对它们进行过滤以获得子集 DF:

df[df.Phrase != "[]"]

空列表 [] 计算结果为 False

df[df.Phrase.astype(bool)]

                       Phrase Sentiment
0               [good, movie]  positive
1  [woow, is, it, very, good]  positive

设置

df = pd.DataFrame([
        [['good', 'movie'], 'positive'],
        [['woow', 'is', 'it', 'very', 'good'], 'positive'],
        [[], 'negative'],
        [[], 'pOSITIVE']
    ], columns=['Phrase', 'Sentiment'])