Issue
I have a string of numbers in this format "IIDDDDDDDD" where "I" are the integers and "D" are the decimals and the string always contains 10 numbers.
I need to format it as II.DDDDDDDD but some times after formatting the number is eg: 00.12345678. I tried using .lstrip('0') but it removes both zeros before the decimal separator and it returns ".12345678" instead of "0.12345678"
df_operacoes['PU Parte'] = df_operacoes['PU Parte'].map(lambda x: f'{x[:2]}.{x[2:]}')
df_operacoes['PU Parte'] = df_operacoes['PU Parte'].str.lstrip('0')
df_operacoes['PU ContraParte'] = df_operacoes['PU ContraParte'].map(lambda x: f'{x[:2]}.{x[2:]}')
df_operacoes['PU ContraParte'] = df_operacoes['PU ContraParte'].str.lstrip('0')
Thanks in advance
Solution
Although it's unclear why you'd choose a representation like this to begin with (perhaps you didn't and you just have to work with it), the problem is very straightforward and so can the solution be:
if df_operacoes['PU Parte'][:2] == '00':
df_operacoes['PU Parte'] = df_operacoes['PU Parte'][1:]
There's nicer solutions possible for more variations of this representation (for example if you also have IIIDDDDDDD
cases, etc. - but that doesn't appear to be the case.
Your comment indicated this was about a DataFrame
- then the below would work:
from pandas import DataFrame
df_operacoes['PU Parte'] = df_operacoes['PU Parte'].apply(lambda s: f'{s[1:2]}.{s[2:]}' if s.startswith('00') else f'{s[:2]}.{s[2:]}')
Answered By - Grismar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.