简体   繁体   中英

How to find number within a string in dataframe and re-format that number using thousands separator?

I have the below example

df = pd.DataFrame({'City': ['Houston', 'Austin', 'Hoover','NY','LA'],
                   'Rules': ['ACH_CM > 28419581.51 and AMT_PM > 30572998.00 and AMT_PPM > 30572998.00 and AMT_CM > 30572998.00'
                             , 'MAA_PM and _AMT_PPM > 30572998.00 and _AMT_PM > 16484703.01 and AMT_CM > 28419581.51'
                             , 'MAA_PM and AMT_CM > 284 and AMT_PM > 30572998.00 and AMT_PPM > 30572998.00 and AMT_PPPM > 30572998.00 and ACH_AMT_PPM > 16484703.01'
                            ,'MAA_CM'
                            ,'_AMT_PPM > 30572.00']},columns=['City', 'Rules'])

Desired output:

City    Rules
Houston ACH_CM > 28,419,581.51 and AMT_PM > 30,572,998.00 and AMT_PPM > 30,572,998.00 and AMT_CM > 30,572,998.00
Austin  MAA_PM and _AMT_PPM > 30,572,998.00 and _AMT_PM > 16,484,703.01 and AMT_CM > 28,419,581.51
Hoover  MAA_PM and AMT_CM > 284 and AMT_PM > 30,572,998.00 and AMT_PPM > 30,572,998.00 and AMT_PPPM > 30,572,998.00 and ACH_AMT_PPM > 16,484,703.01
NY      MAA_CM
LA      AMT_PPM > 30,572.00

I believe I should be using "{0:,.0f}".format but not sure how to apply it.

This might be useful:

if len("%0.f" % floating.number) >= 5:
    print ('do something') 

This should work.

def _format(x):
    unformatted = re.findall("\d+\.\d+", df['Rules'].iloc[0])
    formatted = ['{:,}'.format(float(x)) for x in unformatted]
    for i in range(len(unformatted)):
        x = x.replace(unformatted[i], formatted[i])
    return x

df['Rules'] = df['Rules'].map(_format)

Try this

df['Rules'] = df.Rules.apply(lambda x: re.sub("\d+\.\d+", my_func, x))

where my_func is defined below:

def my_func(matchobj):
    f = float(matchobj.group(0))
    return "{0:,.2f}".format(f)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM