How To Transform a Number from Decimal Format to Custom Format?

Question:

I have a dataframe in Python where two columns are filled with numbers in decimal format, eg:

a) 1.02234583
b) 0.98232131

I have to transform the columns values into a specific format that goes like:

a) 0102234583
b) 0098232131

The mandatory length for the field is 10 characters (2 integers and 8 decimals) and the separator " . " has to be removed.

def calculator_pu():
    base = dataframe
    base['PU Parte'] = 0
    base['PU ContraParte'] = 0
    base = base.reset_index(drop=True)
    base['PU Parte'] = base['Curva Parte'] / base['Valor Base']
    base['PU ContraParte'] = base['Curva ContraParte'] / base['Valor Base']
    base['PU ContraParte'] = base['PU ContraParte'].round(decimals=8)
    base['PU Parte'] = base['PU Parte'].round(decimals=8)
    return base

The values are stored in base[‘PU Parte’] and base[‘PU ContraParte’].

Thanks!

Asked By: pedrosjo

||

Answers:

A simple method, multiply by 10^8, convert to int, then string, and zfill:

df['col'] = (df['col'].mul(10**8)
             .astype(int).astype(str)
             .str.zfill(10)
            )

As function:

def calculator_pu(s):
    return s.mul(10**8).astype(int).astype(str).str.zfill(10)

base[['PU Parte', 'PU ContraParte']] = base[['PU Parte', 'PU ContraParte']].apply(calculator_pu) 

Example output:

     PU Parte PU ContraParte
0  0102234582     0098232131
Answered By: mozway
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.