How remove zeros and round multiple columns in a pandas dataframe
I have a pandas dataframe like this:
df = pd.DataFrame([
{'A': 'aaa', 'B': 5.56000000, 'C': 0.01000000, 'D': 1.00000000, 'E': 0.00001000},
{'A': 'bbb', 'B': 0.49000000, 'C': 0.00100000, 'D': 0.01000000, 'E': 0.00010000},
{'A': 'ccc', 'B': 1.70000000, 'C': 0.10000000, 'D': 0.10000000, 'E': 0.00100000},
{'A': 'ddd', 'B': 5.35000000, 'C': 0.00001000, 'D': 0.00001000, 'E': 0.01000000},
{'A': 'eee', 'B': 6.00000000, 'C': 16.00000000, 'D': 0.00000100, 'E': 1.00000000},
])
A B C D E
0 aaa 5.56000000 0.01000000 1.00000000 0.00001000
1 bbb 0.49000000 0.00100000 0.01000000 0.00010000
2 ccc 1.70000000 0.10000000 0.10000000 0.00100000
3 ddd 5.35000000 0.00001000 0.00001000 0.01000000
4 eee 6.00000000 16.00000000 0.00000100 1.00000000
I need remove trailing zeros and at the same time, round values after the comma for their integer values
Getting a dataframe like this:
A B C D E
0 aaa 5.56 0.01 1 0.00001
1 bbb 0.49 0.001 0.01 0.0001
2 ccc 1.70 0.1 0.1 0.001
3 ddd 5.35 0.00001 0.00001 0.01
4 eee 6.00 16 0.000001 1
Note: column B round 2 value after comma and columns C, D, E trailing zeros and round as appropriate
How i can make those transformation? y try the following solution:
df[['C', 'D', 'E']] = df[['C', 'D', 'E']].astype(str).apply(lambda x: x.str.rstrip('0'))
but i get this:
A B C D E
0 aaa 5.56 0.01 1. 1e-05
1 bbb 0.49 0.001 0.01 0.0001
2 ccc 1.7 0.1 0.1 0.001
3 ddd 5.35 1e-05 1e-05 0.01
4 eee 6.0 16. 1e-06 1.
Thanks in advance!
Solution 1:
If you are doing it just to take the final output, then this works.
df['temp'] = df['B'].astype('float')
df['B'] = df['temp'].astype('string')
But surely, if you want to do more operations on it, you will have to change the type again and that can mess it up.