Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas - Column with count of decimal places

Tags:

python

pandas

I have a dataframe with the following column (dtype='O'):

OUTPUT
1
0
3e-09
NaN
0.4
5.67

And would like to add a new column with the count of decimal places for numbers less than 0:

OUTPUT   DECIMAL_PLACES
1         0
0         0
3e-09     9
NaN       NaN
0.4       1
5.67      0

I have tried naively to convert to string and then to split('.') but the scientific notation doesn't like it. Note: I have a large dataset and it's not very easy to take a glance at where the scientific notations are.

like image 239
Pab Avatar asked Sep 01 '25 22:09

Pab


1 Answers

This is in essence a -log10 operation. For example:

>>> -np.floor(np.log10(df['data']))
0   -0.000000
1         inf
2    9.000000
3         NaN
4    1.000000
Name: data, dtype: float64

0 is here mapped on inf. But we can fix that later. For example:

df['places'] = -np.floor(np.log10(df['data']))
df.loc[np.isinf(df['places']), 'places'] = 0

This gives us:

>>> df
           data  places
0  1.000000e+00    -0.0
1  0.000000e+00     0.0
2  3.000000e-09     9.0
3           NaN     NaN
4  4.000000e-01     1.0
like image 161
Willem Van Onsem Avatar answered Sep 03 '25 11:09

Willem Van Onsem