繁体   English   中英

如何使用正则表达式按给定范围获取匹配结果?

[英]How to get match result by given range using regular expression?

我坚持使用我的代码来获得给定范围内的所有返回匹配。 我的数据样本是:

        comment
0       [intj74, you're, whipping, people, is, a, grea...
1       [home, near, kcil2, meniaga, who, intj47, a, l...
2       [thematic, budget, kasi, smooth, sweep]
3       [budget, 2, intj69, most, people, think, of, e...

我想得到结果:(其中给定的范围是 intj1 到 intj75)

         comment
0        [intj74]   
1        [intj47]    
2        [nan]   
3        [intj69]

我的代码是:

df.comment = df.comment.apply(lambda x: [t for t in x if t=='intj74'])
df.ix[df.comment.apply(len) == 0, 'comment'] = [[np.nan]]

我不确定如何使用正则表达式来查找 t=='range' 的范围。 或者任何其他想法来做到这一点?

提前致谢,

Pandas Python 新手

您可以将[t for t in x if t=='intj74']替换为例如,

[t for t in x if re.match('intj[0-9]+$', t)]

甚至

[t for t in x if re.match('intj[0-9]+$', t)] or [np.nan]

如果没有匹配项,它也会处理这种情况(这样就不需要使用df.ix[df.comment.apply(len) == 0, 'comment'] = [[np.nan]] ) 这里的“技巧”是空列表的计算结果为False以便or在这种情况下返回其正确的操作数。

我也是pandas新手。 您可能以不同的方式初始化了 DataFrame。 无论如何,这就是我所拥有的:

import pandas as pd

data = {
    'comment': [
        "intj74, you're, whipping, people, is, a",
        "home, near, kcil2, meniaga, who, intj47, a",
        "thematic, budget, kasi, smooth, sweep",
        "budget, 2, intj69, most, people, think, of"
    ]
}
print(df.comment.str.extract(r'(intj\d+)'))

暂无
暂无

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

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