从python中的字符串中提取特定模式

问题描述 投票:1回答:3

我在Dataframe列中包含以下数据(包含大约100行)。

需要从每行的DF中提取CK字符串(CK-36799-1523333)。

  • 注意:receipt_id不是固定的.Ck数据可能包含一些不同的变量。

数据:

{"currency":"US","Cost":129,"receipt_id":"CK-36799-1523333","af_customer_user_id":"33738413"}

{"currency":"INR","Cost":429,"receipt_id":"CK-33711-15293046","af_customer_user_id":"33738414"}

{"currency":"US","Cost":229,"receipt_id":"CK-36798-1523333","af_customer_user_id":"33738423"}

{"currency":"INR","Cost":829,"receipt_id":"CK-33716-152930456","af_customer_user_id":"33738214"}

  {"currency":"INR","Cost":829,"order_id":"CK-33716-152930456","af_customer_user_id":"33738214"}

  {"currency":"INR","Cost":829,"suborder_id":"CK-33716-152930456","af_customer_user_id":"33738214"}

结果

CK-36799-1523333
CK-33711-15293046
CK-36798-1523333
CK-33716-152930456

我尝试了str.find('CK-')函数,但未获得预期结果。需要建议

python pandas dataframe extract startswith
3个回答
0
投票

尝试使用正则表达式

import re

...
for line in data:
    res = re.findall(r"CK\-[0-9]+\-[0-9]+", line)
    if len(res) != 0:
        print(res[0])

0
投票

使用Series.str.extract

df['new'] = df['col'].str.extract(r"(CK\-\d+\-\d+)", expand=False).fillna('no match')
print (df)
                                                 col                 new
0  {"currency":"US","Cost":129,"receipt_id":"CK-3...    CK-36799-1523333
1  {"currency":"INR","Cost":429,"receipt_id":"CK-...   CK-33711-15293046
2  {"currency":"US","Cost":229,"receipt_id":"CK-3...    CK-36798-1523333
3  {"currency":"INR","Cost":829,"receipt_id":"CK-...  CK-33716-152930456
4    {"currency":"INR","Cost":829,"order_id":"CK-...  CK-33716-152930456
5    {"currency":"INR","Cost":829,"suborder_id":"...  CK-33716-152930456

另一个解决方案是循环字典并选择第一个匹配,如果不存在,添加默认值:

import ast

f = lambda x: next(iter(v for v in ast.literal_eval(x).values() 
                        if str(v).startswith('CK-')), 'no match')
df['new'] = df['col'].apply(f)

0
投票

假设这是一个csv文件,那么我们可以像这段代码一样找到它。

import re

pattern = re.compile(r'CK-36799-1523333)')
ck_list = []

with open('ck.csv', 'r') as f:  ## where ck.csv is the file you shared above
    for i in f:
        if pattern.search(i):
            ck_list.append(i.split(',')[0].strip())
© www.soinside.com 2019 - 2024. All rights reserved.