首页 > 解决方案 > 在python pandas中多次出现相同分隔符之间提取字符串

问题描述

“测试”列包含多次出现相同分隔符的字符串。我正在尝试获取这些分隔符内的字符串。你能帮忙吗?

例子:

Test
|||||CHNBAD||POC-RM0EP7-01-A

我的代码:

df["Fetch"]=df["Test"].str.rsplit("|", 2).str[-2]

但它给了我一个输出为POC-RM0EP7-01-A.

我正在寻找从字符串中获取“ CHNBAD ”

标签: pythonpandassubstring

解决方案


使用您显示的示例,请尝试以下操作。我们可以str.extract在这里使用函数 pf Pandas。在列上应用str.extract函数Test并创建Fetch在 DataFrame 中命名的新列。

df['Fetch'] = df['Test'].str.extract(r'^\|+([^|]*)\|.*',expand=False)

DataFrame 将如下所示:

    Test                            Fetch
0   |||||CHNBAD||POC-RM0EP7-01-A    CHNBAD

正则表达式的解释:

^\|+     ##Matching 1 or more matches of | from starting of value.
([^|]*)  ##Creating 1st capturing group which has everything till next | comes.
\|.*     ##Matching | and everything till last of value.

推荐阅读