updating only decimal with trailing zero

Viewed 45

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

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
2 Answers

I would do it following way

import pandas as pd
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'])
def stringify(x):
    return '{:.2f}'.format(x) if x%1 else '{:.0f}'.format(x)
df['min_credit'] = df['min_credit'].apply(stringify)
print(df)

output

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

Explanation: if rest of division by 1 is non-zero this is non-integer else it is integer, depending on that either format as .2f (2 digits after .) or .0f (no digits after .). Logic is encased in function, which is applied to selected column.

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
Related