【问题标题】:Converting Floats to String in Mixed Type DF Column Uses Scientific Notation将混合类型 DF 列中的浮点数转换为字符串使用科学记数法
【发布时间】:2019-10-03 18:50:58
【问题描述】:

我有一个数据框,其中有一列正在以混合类型读入。

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

我想将列转换为字符串,但是当我这样做时,任何长小数都会转换为科学记数法。如何以十进制表示法保留所有小数?

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

期望的输出:

    mix
0   a
1   6
2   0.23423
3   False
4   0.000000000023425

【问题讨论】:

    标签: python pandas scientific-notation mixed-type


    【解决方案1】:

    可以使用numpy的format_float_positional函数,如下。

    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)
    

    输出:

    0                    a
    1                    6
    2              0.23423
    3                False
    4    0.000000000023425
    

    【讨论】:

    • 如果x 已经是float 的一个实例,那你为什么还要让它float(x) 呢?另外,为什么try/catch 块? np.format_float_positional 是否有可能引发错误?
    • 好地方!它们是原始方法失败的残余物。我已经更新了答案。
    猜你喜欢
    • 2014-09-25
    • 2014-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-10
    • 1970-01-01
    • 2019-04-22
    • 1970-01-01
    相关资源
    最近更新 更多