【问题标题】:how can we convert string to float?我们如何将字符串转换为浮点数?
【发布时间】:2019-05-21 11:39:20
【问题描述】:

嗨,我试图在 jupyter notebook 中执行一个包含 txt 文件的单元格,我做了这样的事情:

dataset = numpy.loadtxt("C:/Users/jayjay/learning/try.txt", delimiter=",", skiprows=1)
# split into input (X) and output (Y) variables
X=dataset[:100,2:4]
Y=dataset[:100,4]

当我试图运行它时,我得到了这个错误:

ValueError                                Traceback (most recent call last)
<ipython-input-64-d2d2260af43e> in <module>
----> 1 dataset = numpy.loadtxt("C:/Users/jayjay/learning/try.txt", delimiter=",", skiprows=1)
      2 # split into input (X) and output (Y) variables
      3 X=dataset[:100,2:4]
      4 Y=dataset[:100,4]


    ValueError: could not convert string to float: 'not 1'

我在 try.txt 中有一个类似的数据:

135,10,125,10,1
230,16,214,19,not 1
226,16,210,19,1
231,16,215,19,not 1
205,16,189,17,not 1

我该如何解决这个错误?我是一个自学新手。谁能帮我解决这个问题?

【问题讨论】:

  • 哪一行出现错误。因为在上面的行中,您没有将字符串转换为浮点数。
  • not 1 导致错误;将属性从名义转换为数字
  • 第一行出错
  • 是的,我知道不是 1 会导致错误。我该如何解决?
  • 我已经编辑了我的问题

标签: python numpy jupyter


【解决方案1】:

很高兴您提供了文件示例:

In [1]: txt="""135,10,125,10,1 
   ...: 230,16,214,19,not 1 
   ...: 226,16,210,19,1 
   ...: 231,16,215,19,not 1 
   ...: 205,16,189,17,not 1"""                                               

loadtxt 接受字符串列表代替文件:

In [2]: np.loadtxt(txt.splitlines(),delimiter=',')                           
...
ValueError: could not convert string to float: 'not 1'

它试图返回一个浮点数组,但not 1 字符串会出现问题:

genfromtxt 类似,但在可以创建浮动时给出nan

In [3]: np.genfromtxt(txt.splitlines(),delimiter=',')                        
Out[3]: 
array([[135.,  10., 125.,  10.,   1.],
       [230.,  16., 214.,  19.,  nan],
       [226.,  16., 210.,  19.,   1.],
       [231.,  16., 215.,  19.,  nan],
       [205.,  16., 189.,  17.,  nan]])

您可以跳过问题栏:

In [4]: np.loadtxt(txt.splitlines(),delimiter=',', usecols=[0,1,2,3])        
Out[4]: 
array([[135.,  10., 125.,  10.],
       [230.,  16., 214.,  19.],
       [226.,  16., 210.,  19.],
       [231.,  16., 215.,  19.],
       [205.,  16., 189.,  17.]])

或者因为无论如何你要将数组拆分为两个数组:

In [8]: np.genfromtxt(txt.splitlines(),delimiter=',', usecols=[0,1,2,3], dtype=int)                                                               
Out[8]: 
array([[135,  10, 125,  10],
       [230,  16, 214,  19],
       [226,  16, 210,  19],
       [231,  16, 215,  19],
       [205,  16, 189,  17]])
In [9]: np.genfromtxt(txt.splitlines(),delimiter=',', usecols=[4], dtype=None, encoding=None)                                                     
Out[9]: array(['1', 'not 1', '1', 'not 1', 'not 1'], dtype='<U5')

dtype=None 让它为每一列选择合适的数据类型。

In [10]: np.genfromtxt(txt.splitlines(),delimiter=',', dtype=None, encoding=N
    ...: one)                                                                
Out[10]: 
array([(135, 10, 125, 10, '1'), (230, 16, 214, 19, 'not 1'),
       (226, 16, 210, 19, '1'), (231, 16, 215, 19, 'not 1'),
       (205, 16, 189, 17, 'not 1')],
      dtype=[('f0', '<i8'), ('f1', '<i8'), ('f2', '<i8'), ('f3', '<i8'), ('f4', '<U5')])

这是一个结构化数组,每列都有一个field。并且具有更高级的 dtype 规范:

In [13]: np.genfromtxt(txt.splitlines(),delimiter=',', dtype='4i,U5', encoding=None)                                                             
Out[13]: 
array([([135,  10, 125,  10], '1'), ([230,  16, 214,  19], 'not 1'),
       ([226,  16, 210,  19], '1'), ([231,  16, 215,  19], 'not 1'),
       ([205,  16, 189,  17], 'not 1')],
      dtype=[('f0', '<i4', (4,)), ('f1', '<U5')])
In [14]: _['f0']                                                             
Out[14]: 
array([[135,  10, 125,  10],
       [230,  16, 214,  19],
       [226,  16, 210,  19],
       [231,  16, 215,  19],
       [205,  16, 189,  17]], dtype=int32)
In [15]: __['f1']                                                            
Out[15]: array(['1', 'not 1', '1', 'not 1', 'not 1'], dtype='<U5')

到目前为止,我还没有尝试解析或转换那些“非 1”字符串。我们可以构造一个converter,把它变成一个数字,比如0。

如果我定义一个转换器函数,比如:

def foo(astr):
    if astr==b'not 1':
        astr = b'0'
    return int(astr)

In [31]: np.genfromtxt(txt.splitlines(),delimiter=',', converters={4:foo}, dtype=int)                                                            
Out[31]: 
array([[135,  10, 125,  10,   1],
       [230,  16, 214,  19,   0],
       [226,  16, 210,  19,   1],
       [231,  16, 215,  19,   0],
       [205,  16, 189,  17,   0]])

或者如果转换器返回一个浮点数:

def foo(astr):
    if astr==b'not 1':
        astr = b'0'
    return float(astr)
In [39]: np.genfromtxt(txt.splitlines(),delimiter=',', converters={4:foo})   
Out[39]: 
array([[135.,  10., 125.,  10.,   1.],
       [230.,  16., 214.,  19.,   0.],
       [226.,  16., 210.,  19.,   1.],
       [231.,  16., 215.,  19.,   0.],
       [205.,  16., 189.,  17.,   0.]])

【讨论】:

    【解决方案2】:

    用 pandas 读取文件:

    df = pandas.read_csv(file, sep = ',')
    numpydata = df.to_numpy() # will give a numpy array
    

    【讨论】:

    • 试过了,返回这个错误----IndexError: too many indices for array----on the line----> 3 X=dataset[:100,2:4]
    • 该函数的结果是一个数据框,而不是一个 numpy 数组。您需要使用不同的索引
    猜你喜欢
    • 1970-01-01
    • 2011-11-25
    • 1970-01-01
    • 2018-02-15
    • 2011-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多