Henrique Andrade
Henrique Andrade

Reputation: 991

Pandas how to truncate small float values

I'm using pandas.DataFrame.round to truncate columns on a DataFrame, but I have a column of p-values that have small values, which are being rounded to zero. For example, all the values bellow are being rounded to 0.

p-value
2.298564e-17
6.848231e-91   
1.089847e-10  
9.390048e-04   
5.628517e-35  
4.621786e-19   
4.601818e-54 
9.639073e-19  

I want something like

p-value
2.29e-17
6.84e-91   
1.08e-10  
9.39e-04   
5.62e-35  
4.62e-19   
4.60e-54 
9.63e-19

Upvotes: 2

Views: 860

Answers (2)

Rob Raymond
Rob Raymond

Reputation: 31156

Numpy has functions for this.

data = """p-value
2.298564e-17
6.848231e-91   
1.089847e-10  
9.390048e-04   
5.628517e-35  
4.621786e-19   
4.601818e-54 
9.639073e-19"""
a = [x for x in data.split("\n")]
df = pd.DataFrame({"p-value":a[1:]})
df["p-value"] = df["p-value"].astype(np.float)
df["p-value"].apply(lambda x: np.format_float_scientific(x, precision=2))

output

0     2.3e-17
1    6.85e-91
2    1.09e-10
3    9.39e-04
4    5.63e-35
5    4.62e-19
6    4.60e-54
7    9.64e-19
Name: p-value, dtype: object

Upvotes: 2

Quang Hoang
Quang Hoang

Reputation: 150735

not quite truncate, but rather round:

df['p-value'].apply(lambda x: f'{x:.2e}')

Output:

0    2.30e-17
1    6.85e-91
2    1.09e-10
3    9.39e-04
4    5.63e-35
5    4.62e-19
6    4.60e-54
7    9.64e-19
Name: p-value, dtype: object

Upvotes: 2

Related Questions