【问题标题】:Query a pandas dataframe column for a text phrase that may or may not have words within that phrase在 pandas 数据框列中查询一个文本短语,该短语中可能有也可能没有单词
【发布时间】:2018-09-16 21:47:43
【问题描述】:

目标:在 pandas 数据框列中查询一个文本短语,该短语中可能有也可能没有单词。在高层次上,一个短语是“word1 word2”。在 word1 和 word 2 之间可能有也可能没有其他词。

这听起来像是一个骗局,但是我在这里尝试了 SO 答案:

How to extract a substring from inside a string in Python?

Regular expression: matching and grouping a variable number of space separated words

Match text between two strings with regular expression

Extract text information between two define text

还有一些其他的,他们都错过了 word1 和 word2 之间没有单词的情况。

这些投票率高的解决方案都依赖于 word1 和 word2 之间的 (.+?)。

例如:word1(.+?)word2

如果 word1 和 word2 之间有 1+ 个单词,则上述方法效果很好。但是,如果 word1 和 word2 之间没有单词,那么它不会返回任何结果,但是我希望它在这种特殊情况下也能返回结果,因为文本短语包含 word1 word2。

此外,数据将被提前清理,因此无需考虑大写、逗号或其他虚假字符。

我的代码和试验如下。代替 word1 word2 我使用“pieces Delivered”作为文本短语。

请注意,他们都错过了第一个示例,即“已交付的作品”之间没有中间词。它应该返回“一些按时交付的物品”以及其他带有“件......交付”的行。

提前致谢。

import pandas as pd
df = pd.Series(['a', 'b', 'c', 'some pieces delivered on time', 'all pieces not delivered', 'most pieces were never delivered at all', 'the pieces will never ever be delivered', 'some delivered', 'i received broken pieces'])

print("Baseline - Desired results SHOULD contain:\n", df.iloc[3:7])

# The following options all miss one or more rows from the desired results. 
# Just uncomment rgx = to run a regex. 
rgx = r'pieces\s(.*?)\sdelivered'
#rgx = r'pieces\s(\w*)\sdelivered'
#rgx = r'pieces\s(\w*)+\sdelivered'
#rgx = r'pieces\s(\w)*\sdelivered'
#rgx = r'pieces\s(\w+\s)+\sdelivered'
#rgx = r'pieces\s(.*)\sdelivered'
#rgx = r'pieces\s+((%s).*?)\sdelivered'

df2 = df[df.str.contains(rgx)]
print("\nActual results were:\n", df2)

【问题讨论】:

  • df.replace('^((?!pieces.*delivered).)*$',float('nan'),regex=True).dropna() 这应该可以工作

标签: python regex python-3.x pandas


【解决方案1】:

第二个'\s' 位置错误。仅当两个单词不相邻时才需要它:

df[df.str.contains(r'pieces\s(?:.+?\s)?delivered')]
#3              some pieces delivered on time
#4                   all pieces not delivered
#5    most pieces were never delivered at all
#6    the pieces will never ever be delivered

【讨论】:

  • 你甚至需要\s 你甚至需要捕获(.*?)
  • @Onyambu 必须至少有一些分隔符。也许不是空格,但由于我不知道更好,所以我会保持原样。
  • 你是对的。在这种情况下,您还需要第二个单词的分隔符。为了让它成为一个词。换句话说,不被包含。有道理
  • 等等为什么要捕获它?还有为什么要使用+??如果中间什么都没有怎么办? +
  • 无论如何都得走了,但我的++1会留给你
猜你喜欢
  • 2021-12-26
  • 1970-01-01
  • 2020-05-16
  • 1970-01-01
  • 2019-06-27
  • 1970-01-01
  • 1970-01-01
  • 2015-08-28
  • 1970-01-01
相关资源
最近更新 更多