Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

updating only decimal with trailing zero

How can we update only the decimal values of the column with trailing zeros if there are only one digit after decimal.

Example dataframe:

df = pd.DataFrame(data=[[0.3, 0.3], [0.5, 1], [0.400, 0.4], [0.2, 5],[1.2, 1.55]],
    columns=['credit', 'min_credit'])

Executing the below code changes the int as well

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df[min_required_credit] = df[min_credit].map('{:.2f}'.format)

Expected result:

credit min_credit
0.3 0.30
0.5 1
0.400 0.40
0.2 5
1.2 1.55

>Solution :

You can post-process with a simple regex and str.replace:

df['min_credit'].map('{:.2f}'.format).str.replace(r'\.0+$', '', regex=True)

output:

0    0.30
1       1
2    0.40
3       5
4    1.55
Name: min_credit, dtype: object

With assignment:

df['min_required_credit'] = (df['min_credit']
                             .map('{:.2f}'.format)
                             .str.replace(r'\.0+$', '', regex=True)
                            )

output:

   credit  min_credit min_required_credit
0     0.3        0.30                0.30
1     0.5        1.00                   1
2     0.4        0.40                0.40
3     0.2        5.00                   5
4     1.2        1.55                1.55

regex:

\.    # a literal dot
0+    # one or more 0
$     # the end of line
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading