【问题标题】:find column and row index on specific regex match on a pandas dataframe在 Pandas 数据帧上查找特定正则表达式匹配的列和行索引
【发布时间】:2018-02-06 04:06:30
【问题描述】:

假设我有一个 pandas 数据框,其单元格中包含字符串内容。

找到与特定正则表达式匹配的字符串然后返回元组列表及其各自的行和列索引的最佳方法是什么?

即,

import pandas as pd
mydf = pd.DataFrame({'a':['hello', 'world'], 'b': ['hello', 'folks']})

def findIndex(mydf, regex):
    return regex_indexes

如果我这样做:

regex = r"hello"
findIndex(mydf, regex) # it'd return [(0,0), (0,1)],

如果我这样做:

regex = r"matt"
findIndex(mydf, regex) # it'd return [(-1,-1)],

如果我这样做:

regex = r"folks"
findIndex(mydf, regex) # it'd return [(1,1)], 

我可以在 pd.DataFrame 上做一个双 for 循环,但想知道其他想法是否更好......

【问题讨论】:

  • 不需要双循环。 None 不匹配不是更好吗?
  • @AntonvBR 好电话,是的 None 也可以工作,可能是一个更好的主意

标签: python regex pandas


【解决方案1】:

您可以尝试使用applystr.matchnonzero

def findIdx(df, pattern):
    return df.apply(lambda x: x.str.match(pattern)).values.nonzero()

findIdx(mydf, r"hello")
(array([0, 0]), array([0, 1]))
  • df.apply(lambda x: x.str.match(pattern)).values 返回与df 相同大小的数组,其中True 表示匹配,False 否则。

  • 然后我们使用nonzero 来查找1(True) 部分的索引。

它将返回与数组元组中的模式匹配的索引。如果你需要 元组列表,使用list(zip(*findIdx(mydf, r"hello")))

[(0, 0), (0, 1)] 

np.transpose(findIdx(mydf, r"hello"))


如果需要在没有找到的情况下返回None,可以尝试

def findIdx(df, pattern):
    ret = df.apply(lambda x: x.str.match(pattern)).values.nonzero()
    return None if len(ret[0]) == 0 else ret

注意:str.match 在钩子下使用re.match。在此示例函数中,它将匹配 pattern 开头的字符串。如果要查找字符串是否包含pattern 作为子字符串,请使用str.contains 而不是str.match

【讨论】:

  • 感谢这是正确的方向。我有一个跟进 q 虽然,它似乎不像典型的正则表达式。如果我确实 findIdx(pd.DataFrame({'a': ['br', 'a hello,'], 'b':['das','hello']}), r"hel"),它会只匹配第 1 行第 1 列上的那个,但不匹配第 0 列上的那个...关于如何为更一般的情况编写模式部分的任何建议?
  • @Dnaiel 我想如果您想查找字符串是否包含子字符串,您可能会使用str.contains
  • .to_numpy().nonzero()version 0.24.0起将是必需的
猜你喜欢
  • 2022-01-24
  • 1970-01-01
  • 2011-03-31
  • 2019-05-23
  • 1970-01-01
  • 1970-01-01
  • 2017-07-11
  • 2021-06-16
  • 2018-07-20
相关资源
最近更新 更多