Reputation: 2797
I have a data frame like as below. I am trying to round the number to 1 decimal. But in some cases, if a number is 0.9 or below, I need to show the number with rounding exactly with the least precision
import pandas as pd
df_input = pd.read_csv('test.csv')
print(df_input)
The result of the data frame,
Cateogry Consumption
0 Category 1 31.248175
1 Category 1 0.401825
2 Category 2 0.178149
3 Category 2 6.538878
4 Category 3 0.011308
5 Category 3 0.023273
6 Category 4 0.000533
7 Category 5 0.126154
I am rounding up the above data frame as like below,
print(df_input.round(1))
Cateogry Consumption
0 Category 1 31.2
1 Category 1 0.4
2 Category 2 0.2
3 Category 2 6.5
4 Category 3 0.0 // It should show 0.01
5 Category 3 0.0 // It should show 0.02
6 Category 4 0.0 // It should show 0.0005
7 Category 5 0.1
Like I commented in rows 4, 5, 6, It should show the value as the way I show.
Is there anyway can I do that?
Upvotes: 0
Views: 569
Reputation: 1155
If you just want to round the numbers, this should work fine:
from math import floor, log10
df_input["Consumption"] = df_input["Consumption"].apply(lambda x: round(x, max(1, - int(floor(log10(abs(x)))))))
df_input["Consumption"]
#0 31.2000
#1 0.4000
#2 0.2000
#3 6.5000
#4 0.0100
#5 0.0200
#6 0.0005
#7 0.1000
You can deal with trailing zeros via formatting, fe:
format_mapping = {"Consumption": "{:,g}"}
df_input.style.format(format_mapping)
# Cateogry Consumption
#0 Category 1 31.2
#1 Category 1 0.4
#2 Category 2 0.2
#3 Category 2 6.5
#4 Category 3 0.01
#5 Category 3 0.02
#6 Category 4 0.0005
#7 Category 5 0.1
Upvotes: 1