python - 在python pandas中多次出现相同分隔符之间提取字符串
问题描述
“测试”列包含多次出现相同分隔符的字符串。我正在尝试获取这些分隔符内的字符串。你能帮忙吗?
例子:
Test
|||||CHNBAD||POC-RM0EP7-01-A
我的代码:
df["Fetch"]=df["Test"].str.rsplit("|", 2).str[-2]
但它给了我一个输出为POC-RM0EP7-01-A
.
我正在寻找从字符串中获取“ CHNBAD ”
解决方案
使用您显示的示例,请尝试以下操作。我们可以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.
推荐阅读
- python - 以保持元素索引/位置相同的方式更改 numpy 数组的形状
- python - 如何在 Python 中比较具有不同列名(具有相同和不同值)的 2 个 DataFrame
- flutter - 显示喜欢和不喜欢颤动
- css - Clip-path 不会影响 Safari 中元素的顺序
- c++ - 浏览器在收到来自自定义 Web 服务器的 HTTP 响应后关闭连接
- python - Kaggle Titanic-Machine Learning From Disaster with TensorFlow:模型训练无法获得损失值
- c++ - 当参数具有相同名称时,类构造函数不初始化属性
- excel - 为什么我的 VBA 代码存在文件路径错误
- python - 如何使用 selenium 遍历 python 列表,搜索每个项目,抓取数据,然后搜索下一个项目
- java - 仅以有效的方式读取少量 xml 元素