Home > front end >  How to find how many decimal places there are in a column using a pandas dataframe
How to find how many decimal places there are in a column using a pandas dataframe

Time:08-24

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

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

You can do:

df['ColB'].astype(str).str.extract(r'\.(.*)', expand=False).str.len()
  • Related