pythonpandasscientific-notationmixed-type

Converting Floats to String in Mixed Type DF Column Uses Scientific Notation


I have a dataframe with a column that is being read in with mixed types.

df = pd.DataFrame({'mix':['a',6,0.23423,False, 0.000023425]})

I want to convert the column to strings, but when I do so, any long decimals get converted to scientific notation. How do I keep all decimals in decimal notation?

df.astype(str)
    mix
0   a
1   6
2   0.23423
3   False
4   2.3425e-11

Desired output:

    mix
0   a
1   6
2   0.23423
3   False
4   0.000000000023425

Solution

  • You can use the numpy format_float_positional function, as follows.

    import numpy as np
    
    df = pd.DataFrame({'mix':['a',6,0.23423,False, 0.000000000023425]})
    
    def custom_str(x):
        if isinstance(x, float):
            return np.format_float_positional(x)
        return str(x)
    
    df['mix'].apply(custom_str)
    

    Output:

    0                    a
    1                    6
    2              0.23423
    3                False
    4    0.000000000023425