【问题标题】:Converting a string to an integer or float将字符串转换为整数或浮点数
【发布时间】:2021-11-30 15:37:27
【问题描述】:

我有以下列表:

[[1.01782362e-05 1.93798303e-04 7.96163586e-05 5.08812627e-06
  1.39600188e-05 3.94912873e-04 2.33748418e-04 1.22856018e-05]]

当我返回它的类型时,我得到:

<class 'str'>

是否使用了科学记数法(即 e-04)?

在这种情况下,如何将上面的列表转换为整数或浮点数?

谢谢。

编辑

上面的列表sn-p来自“特征”栏下的this CSV file

【问题讨论】:

标签: python list floating-point type-conversion integer


【解决方案1】:

看起来很像你有 NumPy 的数组字符串表示。正如我上面链接的那样,似乎没有一种很好的解析方式,但在你的情况下,这可能并不重要,Pandas 和 Numpy 可以相当容易地到达那里:

import pandas as pd
import numpy as np

# read in the data
df = pd.read_csv("features_thresholds.csv")

# use numpy to parse that column
df.Feature = df.Feature.apply(lambda x: np.fromstring(x[2:-2], sep=' '))

请注意,x[2:-2] 正在修剪前导 [[ 和尾随 ]],否则大多数数据科学教程将使用标准 Pandas 用法。

【讨论】:

  • 如果可以的话,我建议询问给你该文件的人,以更容易解析的其他格式提供给你,例如数组的 JSON 转储可能比您所拥有的更便携
【解决方案2】:

您发布的内容必须是字符串文字的一部分:

s = '[[1.01782362e-05 1.93798303e-04 7.96163586e-05 5.08812627e-06 1.39600188e-05 3.94912873e-04 2.33748418e-04 1.22856018e-05]]'

在什么情况下

list(map(float, s.lstrip('[').rstrip(']').split()))

评估为

[1.01782362e-05, 0.000193798303, 7.96163586e-05, 5.08812627e-06, 1.39600188e-05, 0.000394912873, 0.000233748418, 1.22856018e-05]

【讨论】:

    【解决方案3】:

    我们可以使用python ast(抽象语法树)来高效地处理它

    import ast
    x = '[[1.01782362e-05 1.93798303e-04 7.96163586e-05 5.08812627e-06 1.39600188e-05 3.94912873e-04 2.33748418e-04 1.22856018e-05]]'
    x = ast.literal_eval(x.replace(" ",","))
    print(x)
    

    【讨论】:

    • 使用literal_eval 是个好主意。
    猜你喜欢
    • 2014-04-29
    • 1970-01-01
    • 1970-01-01
    • 2016-02-06
    • 2011-11-25
    • 1970-01-01
    • 2016-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多