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