Sjoerd
Sjoerd

Reputation: 21

How is it possible to show a different number of decimals in one column in Python

I'm trying to get a different number of decimals in one column in a pandas dataframe. I have rounded the values in the concerning columns to the right amount of decimals, however, the whole column shows the maximum number of decimals.

For example I have this dataframe:

df = pd.DataFrame({'Column Name':[1005, 100.5, 10.05, 1.005]})

1005.000
100.500
10.050
1.005

Whereas I want it to be like:

1005
100.5
10.05
1.005

How is this possible?

Upvotes: 2

Views: 351

Answers (2)

kuzand
kuzand

Reputation: 9806

Just set the dtype to object so that the integer 1005 remains integer (otherwise all the values are automatically converted to float64):

df = pd.DataFrame({'Column Name':[1005, 100.5, 10.05, 1.005]}, dtype='O')

df
Out[33]: 
  Column Name
0        1005
1       100.5
2       10.05
3       1.005

Upvotes: 2

Valdi_Bo
Valdi_Bo

Reputation: 30991

One of possible solutions:

df['Column Name'].astype(str).str.extract(r'(\d{4}|.{5})')

Note that the capturing group in the pattern is without name, so the resulting column has name == 0. If you want this column to have some meaningful name, use a named capturing group instead, e.g.:

df['Column Name'].astype(str).str.extract(r'(?P<Number>\d{4}|.{5})')

Upvotes: 0

Related Questions