繁体   English   中英

在熊猫数据框上查找特定正则表达式匹配的列和行索引

[英]find column and row index on specific regex match on a pandas dataframe

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

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

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上执行double for循环,但想知道其他想法是否更好...

你可以尝试使用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找到1True )部分的索引。

它将返回与数组元组中的模式匹配的索引。 如果需要元组列表,请使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM