Reputation: 3432
Hello I have a df such as :
COL1 COL2
0.005554 0.35200000000000004
5.622e-11 0.267
0.006999999999999999 0.307
2.129e-14 0.469
2.604e-14 0.39
1.395e-60 0.27899999999999997
8.589999999999998e-74 0.29600000000000004
1.025e-42 0.4270000000000001
I knwo how to roun the digit in the COL2 by using
df['COL2'] = df['COL2'].round(3)
but if I do the same for COL1 it only displays 0
how can I get instead:
COL1 COL2
0.005 0.352
5.622e-11 0.267
0.007 0.307
2.129e-14 0.469
2.604e-14 0.39
1.395e-60 0.279
8.560e-74 0.296
1.025e-42 0.427
in fact the big issue is here:
it displays : 8.589999999999998e-74
and I would like to keep only 3 number after the coma
8.590e-74
Upvotes: 1
Views: 2125
Reputation: 66
are lines 1 and 3 of the resulting dataframe also 0? because all other lines are 0 when rounded to the 3rd decimal because 5.622e-11 is 0.00000000005622 thus rounded to 3 decimals it is 0.
Upvotes: 0
Reputation: 1632
You don't want to round the values in the first column - rounding means that the lower digits are gone. I think what you actually want to do is to change how Pandas displays the data on screen and not the actual values in the dataframe. The default is already scientific notation.
You can specify the display format for all columns like so (this will be showing the first three digits after the dot):
pd.set_option('display.float_format', lambda x: '%.3f' % x)
Since you want to keep the format of the first one but not of the second you might need to set the format for each column individually. You can use styling for column 2:
df.style.format({'COL2': '{:.3f}')
Edit: Since your answer is for saving to CSV, you'll need to pass this as an argument to to_csv
: float_format='{:.3E}'
. This will save all columns in scientific notation. If you only want this for column 1, you could try the solutions to this question.
Upvotes: 4
Reputation: 6322
Assuming you only want to do this for display purposes, you can set
pd.options.display.precision = 3
print(df)
or to only do so in a temporary context:
with pd.option_context('display.precision', 3):
print(df)
Upvotes: 1