【问题标题】:Converting numpy string array to float: Bizarre?将 numpy 字符串数组转换为浮点数:奇怪?
【发布时间】:2013-03-22 01:10:27
【问题描述】:

所以,这应该是一件非常简单的事情,但无论出于何种原因,我将字符串数组转换为浮点数组的任何操作都不起作用。

我有一个两列数组,如下所示:

Name    Value
Bob     4.56
Sam     5.22
Amy     1.22

我试试这个:

for row in myarray[1:,]:
     row[1]=float(row[1])

还有这个:

for row in myarray[1:,]:
    row[1]=row[1].astype(1)

还有这个:

myarray[1:,1] = map(float, myarray[1:,1])

他们似乎都在做某事,但是当我仔细检查时:

type(myarray[9,1])

我明白了

<type> 'numpy.string_'>

【问题讨论】:

  • 旁白:如果您正在处理混合类型的数据,可能值得您花时间查看pandas。它已经包含了许多您需要重新实现的工具,以便获得纯 numpy 来执行人们通常在名称和数字数据集上执行的那种操作。

标签: python numpy type-conversion


【解决方案1】:

Numpy 数组必须有一个 dtype,除非它是结构化的。由于数组中有一些字符串,它们必须都是字符串。

如果你想拥有一个复杂的dtype,你可以这样做:

import numpy as np
a = np.array([('Bob','4.56'), ('Sam','5.22'),('Amy', '1.22')], dtype = [('name','S3'),('val',float)])

请注意,a 现在是 1d structured array,其中每个元素都是 dtype 类型的元组。

您可以使用字段名称访问这些值:

In [21]: a = np.array([('Bob','4.56'), ('Sam','5.22'),('Amy', '1.22')],
    ...:         dtype = [('name','S3'),('val',float)])

In [22]: a
Out[22]: 
array([('Bob', 4.56), ('Sam', 5.22), ('Amy', 1.22)], 
      dtype=[('name', 'S3'), ('val', '<f8')])

In [23]: a['val']
Out[23]: array([ 4.56,  5.22,  1.22])

In [24]: a['name']
Out[24]: 
array(['Bob', 'Sam', 'Amy'], 
      dtype='|S3')

【讨论】:

    【解决方案2】:

    numpy 数组中对象的类型在该数组的初始化时确定。如果您想稍后更改它,则必须转换数组,而不是该数组中的对象。

    myNewArray = myArray.asType(float)
    

    注意:向上转换是可能的,对于向下转换,您需要 astype 方法。 如需更多信息,请参阅:
    http://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html http://docs.scipy.org/doc/numpy/reference/generated/numpy.chararray.astype.html

    【讨论】:

    • 但是数组有像'Bob'这样的字符串不能转换成浮点数,所以会给出ValueError: could not convert string to float: 'Bob'
    猜你喜欢
    • 2011-07-18
    • 2021-12-28
    • 1970-01-01
    • 2019-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-25
    • 1970-01-01
    相关资源
    最近更新 更多