How to remove .0 from number

Question:

I have one column DOB(Year) in df dataframe, which consist values like below:

DOB(Year)
1990.0
1998.0
2015.0
2017.0

I want to remove .0 from all values.

I have tried

df[DOB(Year)]=df[DOB(Year)].astype(str)
df[DOB(Year)]=df[DOB(Year)].str.replace(".0$", "",regex=True)

But resulting column values are nan.
Can anyone please suggest solution for this?

Asked By: Shital

||

Answers:

Try this:

df[DOB(Year)]=df[DOB(Year)].astype('int')
Answered By: Pavel Kochkin

If you want a safe method that works on numeric/string input:

df['DOB(Year)'] = (pd.to_numeric(df['DOB(Year)'], errors='coerce')
                     .round().convert_dtypes()
                  )

Example (as new column):

   DOB(Year)  DOB(Year)_converted
0     1990.0                 1990
1     1998.0                 1998
2     2015.0                 2015
3     2017.0                 2017
4  2011.0001                 2011
5        abc                 <NA>
Answered By: mozway
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.