2
votes

I have data frame with a object column lets say col1, which has values likes: 1.00, 1, 0.50, 1.54

I want to have the output like the below: 1, 1, 0.5, 1.54 basically, remove zeros after decimal values if it does not have any digit after zero. Please note that i need answer for dataframe. pd.set_option and round don't work for me.

5
Are you certain you have strings? And if you do. Why would you want to store numbers as strings? - Anton vBR
1) it is not duplicate. i checked the given link. - Alexsander
2) i need to have blank value in case of null values so keep it string. - Alexsander
Ok thanks for answers. In the case of 2) though: A null value in number is in the dataframe a np.nan value (displayed as NaN). This means: Not a Number. - Anton vBR

5 Answers

2
votes

If want convert integers and floats numbers to strings with no trailing 0 use this with map or apply:

df = pd.DataFrame({'col1':[1.00, 1, 0.5, 1.50]})

df['new'] = df['col1'].map('{0:g}'.format)
#alternative solution
#df['new'] = df['col1'].apply('{0:g}'.format)
print (df)
   col1  new
0   1.0    1
1   1.0    1
2   0.5  0.5
3   1.5  1.5

print (df['new'].apply(type))
0    <class 'str'>
1    <class 'str'>
2    <class 'str'>
3    <class 'str'>
Name: new, dtype: object
1
votes

I think something like this should work:

if val.is_integer() == True :
    val = int(val)
elif val.is_float() == True :
    val = Decimal(val).normalize()

Assuming that val is a float value inside the dataframe's column. You simply cast the value to be integer. For float value instead you cut extra zeros.

0
votes

A quick-and-dirty solution is to use "%g" % value, which will convert floats 1.5 to 1.5 but 1.0 to 1 and so on. The negative side-effect is that large numbers will be represented in scientific notation like 4.44e+07.

0
votes

Taken from this Stackoverflow answer, I think you'd like to change the display precision of pandas like so:

pd.set_option('precision', 0)
0
votes

How about the str.rstrip method. Like so (assuming your strings are in a list):

a = ["1.00", "1" ,"0.50", "1.50"]

b = [e.rstrip('.0') for e in a]

>>> ['1', '1', '0.5', '1.5']