首页 > 解决方案 > 在 Pandas df 中捕获/过滤文本,其中每一行都有一个唯一的起点

问题描述

我想在字符串中搜索并显示 IBAN 号码。唯一的问题是 IBAN 的起始位置可以变化。我尝试了以下方法,但我只得到了 NaN。

顺便说一句,如果有更好的方法可以随意提出不同的解决方案。

import pandas as pd
data = {'Description': ['some text IBAN xxxx', 'IBAN xxxx', 'some text some text IBAN xxxx']}
df = pd.DataFrame(data, columns = ['Description'])
df['position'] = df['Description'].str.find('IBAN') 
df['IBAN'] = df['Description'].str.slice(start=df['position'], stop=8)
df

在此处输入图像描述

标签: pythonpandasstringfilterslice

解决方案


如果您有来自单个国家/地区的 IBAN,并且 IBAN 始终位于字符串的末尾,您可以尝试从末尾进行字符串切片。例如,对于来自德国的 22 个字符长的 IBAN,您可以执行以下操作:

import pandas as pd
data = {'Description': ['some text IBAN xxxx', 'IBAN xxxx', 'some text some text IBAN xxxx']}
df = pd.DataFrame(data, columns = ['Description'])
df['IBAN'] = df['Description'].apply(lambda x: x.replace(" ", "")[-22:])
df

使用替换,您可以确保您考虑带空格和不带空格的 IBAN。


推荐阅读