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!
CodePudding user response:
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