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

时间:2019-03-06 11:56:35

标签: python pandas dataframe extract startswith

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

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

  • 注意:received_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-')函数,但没有得到预期的结果。需要建议

3 个答案:

答案 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)

答案 1 :(得分:0)

尝试使用正则表达式

sudo launchctl unload /Library/LaunchDaemons/org.jenkins-ci.plist

答案 2 :(得分: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())