how to remove zeros after decimal from string remove all zero after dot

后端 未结 5 1217
傲寒
傲寒 2021-01-15 09:13

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

相关标签:
5条回答
  • 2021-01-15 09:33

    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']
    
    0 讨论(0)
  • 2021-01-15 09:35

    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 讨论(0)
  • 2021-01-15 09:39

    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 讨论(0)
  • 2021-01-15 09:43

    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 讨论(0)
  • 2021-01-15 09:48

    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
    
    0 讨论(0)
提交回复
热议问题