How to find how many decimal places there are in a column using a pandas dataframe

Question:

I have a large dataframe that contains a column with different amount of decimal places. I want to create something like Decimal Places in my example. The goal of this column is to count

df
ColA   ColB   DecimalPlaces 
A      .03    2
B      .003   3
C      10.01  2
D      11.1   1

I tried Below but I can’t get it to work for a whole column on a dataframe

d = decimal.Decimal('56.43256436')

d.as_tuple().exponent
Asked By: foxbundle

||

Answers:

here is one way to do it

split the number at decimal, then take its length

df['decimals']=df['ColB'].astype('str').str.split('.', expand=True)[1].apply(lambda x: len(x))
df
    ColA    ColB    DecimalPlaces   decimals
0      A    0.030               2      2
1      B    0.003               3      3
2      C    10.010              2      2
3      D    11.100              1      1
Answered By: Naveed

I’ve got basically the same as Naveed here, but, well, slightly different:

df['decimals'] = df['ColB'].map(lambda x: str(x).split('.')[1]).apply(len)

no idea what’s faster / more efficient.

Answered By: scotscotmcc

You can do:

df['ColB'].astype(str).str.extract(r'.(.*)', expand=False).str.len()
Answered By: SomeDude
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.