gpt4 book ai didi

python - 匹配 Pandas 中字符和数字的混合

转载 作者:太空宇宙 更新时间:2023-11-04 03:18:53 25 4
gpt4 key购买 nike

我需要从 pandas df 中提取子字符串,并将它们放入一个新列中。我的字符串看起来像:

hj_yu_fb824_as22
jk_yu_fb638

我需要提取:

 fb824
fb638

此外,它们的子字符串可以位于数据框的两个独立列中(尽管只出现一次),因为 df 看起来像:

col1                col2
mf_lp_gn817_ml46 d_nb_05340.gif
desktop_300x250_mf mf_lp_fb824_ml46.html
desktop_300x250_mf dd_lp_ig805.html
desktop_728x90_mf mf_lp_fb824_ml46.html

我想得到这样的东西:

col1                col2                     col3
mf_lp_gn817_ml46 d_nb_05340.gif gn817
desktop_300x250_mf mf_lp_fb824_ml46.html fb824
desktop_300x250_mf dd_lp_ig805.html ig805
desktop_728x90_mf mf_lp_fb824_ml46.html fb824

所以子字符串看起来像:

1) 两个小写字母开头,后接3位数字2) 在两个 '' 之间或只有一个 '' 之间,或在 '_' 和 '.' 之间别的东西

我想到了:

 \_([^()]*)\_

但它只匹配“_”之间的任何内容,而不管上面描述的模式如何。

此外,将正则表达式应用于 pandas 数据框的效率如何?

这是可重现的数据框:

df = DataFrame({'col1': {0: 'mf_lp_gn817_ml46',
1: 'desktop_300x250_mf',
2: 'desktop_300x250_mf',
3: 'desktop_728x90_mf'},
'col2': {0: 'd_nb_05340.gif ',
1: 'mf_lp_fb824_ml46.html ',
2: 'dd_lp_ig805.html ',
3: 'mf_lp_fb824_ml46.html '},
'col3': {0: 'gn817', 1: 'fb824', 2: 'ig805', 3: 'fb824'}})

最佳答案

可能需要更多输入字符串,但对于上述字符串,您可以使用以下正则表达式:

_([a-z]{2}[0-9]{3})[_.]
# this is an underscore
# followed by exactly 2 letters and 3 digits
# followed by an underscore or a dot
# the whole match is captured to group1

对于您上面的字符串,这将是:

mf_lp_gn817_ml46    d_nb_05340.gif           -> gn817
desktop_300x250_mf mf_lp_fb824_ml46.html -> fb824
desktop_300x250_mf dd_lp_ig805.html -> ig805
desktop_728x90_mf mf_lp_fb824_ml46.html -> fb824

参见 a demo on regex101.com .

Python代码:

要将此应用于您的 DataFrame,请参见以下代码:

import pandas as pd
from pandas import DataFrame
import re

df = DataFrame({'col1': {0: 'mf_lp_gn817_ml46',
1: 'desktop_300x250_mf',
2: 'desktop_300x250_mf',
3: 'desktop_728x90_mf'},
'col2': {0: 'd_nb_05340.gif ',
1: 'mf_lp_fb824_ml46.html ',
2: 'dd_lp_ig805.html ',
3: 'mf_lp_fb824_ml46.html '}})

regex = r'_([a-z]{2}[0-9]{3})[_.]'
for index, row in df.iterrows():
for column in row.keys():
m = re.search(regex, row[column])
if m is not None:
df.ix[index, 'col3'] = m.group(1)

关于python - 匹配 Pandas 中字符和数字的混合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35315079/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com