簡體   English   中英

基於列單元格值如何使用 python 從字符串中提取特定的字符編號

[英]based on column cell value how to extract specific no# of character from string using python

就像我們在 Excel 中使用的左公式一樣,我想提取編號。 保單號的特征基於 Insurer 列的列,例如.....

如果保險公司是 HDFC,則僅從 sting 中提取 10 個字符,如果保險公司是 tata,則僅從 sting 中提取 7 個字符。 如果是 HDFC & tata 以外的保險公司,則將其留空。

另請參閱 hdfc 保險帶有許多不同的名稱。

我將如何在 python 中實現這一點

保險公司 保單號 預期 OutPut
高清晰度電視 4509242332 4509242332
塔塔 tatadigit National 塔塔迪格
人機工程學 09082323ab12sd 09082323ab
HDFC 諾蘭英雄 諾蘭英雄
塔塔 97543007356 9754300
塔塔 pqrsequence2o202 pqrsequ
塔塔 987654321 9876543
HDFC 健康人體工學 諾蘭英雄 諾蘭英雄
數字 第1733章
星星 納希霍納爾

您可以借助字典對每個組使用str訪問器:

num = {'hdfc': 10, 'tata': 7}

# identify insurer from first word (can be changed to another method)
group = df['Insurer'].str.extract('(\w+)', expand=False).str.lower()

df['Expected OutPut'] = (df.groupby(group)['Policy no.']
                           .transform(lambda g: g.str[:num[g.name]]
                                             if g.name in num else '')
                        )

output:

            Insurer         Policy no. Expected OutPut
0              Hdfc         4509242332      4509242332
1              Tata  tatadigitNational         tatadig
2         Hdfc ergo     09082323ab12sd      09082323ab
3              HDFC       nolanheroman      nolanherom
4              Tata        97543007356         9754300
5              Tata   pqrsequence2o202         pqrsequ
6              Tata          987654321         9876543
7  HDFC health ergo       nolanheroman      nolanherom
8             Digit         1733choola                
9              star        naahiHonaar                

更新:強制最小長度

num = {'hdfc': 10, 'tata': 7}

group = df['Insurer'].str.extract('(\w+)', expand=False).str.lower()

df['Expected OutPut'] = (df.groupby(group)['Policy no.']
                           .transform(lambda g: g.mask(g.str.len()<num[g.name], '')
                                                 .str[:num[g.name]]
                                             if g.name in num else '')
                        )

output:

            Insurer         Policy no. Expected OutPut
0              Hdfc         4509242332      4509242332
1              Tata  tatadigitNational         tatadig
2         Hdfc ergo     09082323ab12sd      09082323ab
3              HDFC             nolanh                   # example here
4              Tata        97543007356         9754300
5              Tata   pqrsequence2o202         pqrsequ
6              Tata          987654321         9876543
7  HDFC health ergo       nolanheroman      nolanherom
8             Digit         1733choola                
9              star        naahiHonaar                

另一個想法是創建一個助手clipper剪裁器。 m包含每行要裁剪的字符數(假設前 4 個字符是hdfc / tata /other),那么向量化clipper function 可以應用於Policy no. m

import numpy as np

def clipper(string, stop):
    return string[:stop]

m = df.Insurer.str[:4].str.lower().map({"hdfc": 10, "tata": 7}).fillna(0).astype(int)
df["Expected OutPut"] = np.vectorize(clipper)(df["Policy no."], m)

使用np.where檢查下面的答案,Expected_Output_Answer 是計算列

import pandas as pd
import numpy as np

df['Expected_Output_Answer'] = np.where(df['Insurer'].str.contains('hdfc', case=False), 
                                 df['Policy no.'].str[:10],
                                 np.where(df['Insurer'].str.contains('tata', case=False),
                                 df['Policy no.'].str[:7],
                                 ""
                                 )
                                 )
df

Output:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM