从dataframe中删除一个示例

2024-09-28 03:20:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这样的数据帧

     Phrase                          Sentiment

   [ good , movie ]                   positive

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

      []                             negative
      []                              pOSTIVE

列短语类型为object,需要删除包含[]的行 我不知道怎么用python

像这样:

 Phrase                          Sentiment

   [ good , movie ]                   positive

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

Tags: 数据类型objectisitmovieverygood
2条回答

您可以通过str.len()==0检查空列表的存在,并基于此通过执行否定操作来过滤DF。你知道吗

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

enter image description here

要知道存在空列表的行:

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'])

相关问题 更多 >

    热门问题