![](/img/trans.png)
[英]Find Specific Values in a Dataframe and Record the (Row, Column) Index Pair
[英]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循环,但想知道其他想法是否更好...
你可以尝试使用apply
, str.match
和nonzero
。
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
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.