如何将以特定方式替换字符串的函数应用于python数据框系列

时间:2018-07-17 09:22:08

标签: python pandas apply

我正在尝试提出一个替换字符串的函数 “ ORG_CD_XXX> 0.00”和“ ORG_CD_XXX”

此字符串可以出现在给定数据帧行中的任何位置。我试图提出一个可以进行替换的函数,但是当我尝试将其应用于数据框系列时,出现错误IndexError: list index out of range

import pandas as pd
data = {'Rule': 
                ['HAD_MAA_PM and HAD_MAA_PM and ACH_PERC_PM > 66.64 and ACH_PERC_CM > 82.19'
                 ,'HAD_MAA_PM and HAD_MAA_PM and ORG_CD_DDV > 0.00 and ACH_PERC_CM > 82.19'
                 ,'HAD_MAA_PM and HAD_MAA_PM and ORG_CD_DDV > 0.00 and ach_perc_chg_CM <= 0.00 and ACH_PERC_PPM > 48.99']
                }
df=pd.DataFrame.from_dict(data)

def org_cd_replace(text):
    text1=text.split('ORG_CD_')
    text2=[item.replace(' > 0.00',"",1) for item in text1]
    text3=text2[0]+'ORG_CD_'+text2[1]

    return text3

df['Rule'].apply(lambda x:org_cd_replace(x))

1 个答案:

答案 0 :(得分:2)

您的代码很好。您这里遇到的问题是因为某些字符串中没有'ORG_CD_'。 为了解决这个问题,只需添加一个测试:

def org_cd_replace(text):
    if 'ORG_CD_' in text:
        text1=text.split('ORG_CD_')
        text2=[item.replace(' > 0.00','', 1) for item in text1]
        text3=text2[0]+'ORG_CD_'+text2[1]
        return text3
    return text

df = pd.DataFrame(df['Rule'].apply(lambda x:org_cd_replace(x)))

应用lambda函数后,必须在最后添加pd.DataFrame()调用才能获取DataFrame。 毫无疑问,有更好的方法(至少更有效率)来执行此操作。