【问题标题】:search in dataframe with spliting the text通过拆分文本在数据框中搜索
【发布时间】:2019-03-14 16:09:52
【问题描述】:

我有一个由两列组成的数据框,id 和 text。

例如,我想检索文本长度大于 2 的行。

文本长度是文本中的单词数而不是字符数。

我做了以下事情:

df = pd.DataFrame([{'id': 1, 'text': 'Connected to hgfxg debugger'},
                   {'id': 2, 'text': 'fdss debugger - process 6384 is connecting'},
                   {'id': 3, 'text': 'we are'},
                   ])
df = df[df['text'].str.len() > 2]
print(df) #<-- it will print all the sentences above

但这会检索超过 2 个字符的句子(在我们的例子中,是上面的所有句子)。

如何在一行代码中实现我想要的?可能吗?

我可以用不止一个来做,比如:

df['text_len'] = df['text'].map(lambda x: len(str(x).split()))
df = df[df['text_len'] > 2]
print(df) #<-- will print the first two sentences

【问题讨论】:

    标签: python pandas dataframe search


    【解决方案1】:

    换一种方式,你要多于2个句子,所以字符串中需要两个' ',这里我们只算' '多于2个

    df[df['text'].str.count(' ')>2]
    Out[230]: 
       id                                        text
    0   1                 Connected to hgfxg debugger
    1   2  fdss debugger - process 6384 is connecting
    

    【讨论】:

      【解决方案2】:

      你也可以使用:

      df[df.text.str.split('\s+').str.len().gt(2)]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多