代码之家  ›  专栏  ›  技术社区  ›  npross

将python maskedcolumn相乘

  •  0
  • npross  · 技术社区  · 7 年前

    我正在读取一个.html文件中的数据,我只想将data['ra']列乘以15。但是,我得到了一个错误:

    >>> data = ascii.read("Ldwarf.html", format="html", encoding = "ISO-8859-1")  
    >>> data
    
    <Table masked=True length=919>
    designation ra  decl    
    2MASS J00011217+1535355 0.0200472   +15.593194  
    2MASS J00025097+2454141 0.0474917   +24.903917  
    2MASS J00040288-6410358 0.0674667   -64.176611  
    

    >>> data['ra'] 
    <MaskedColumn name='ra' dtype='str10' length=919>
    decimal hr
    0.0200472
    0.0474917
    ...
    23.9783250
    23.9993389
    
    >>> data['ra'] = data['ra'].filled([-9.99])
    >>> data['ra'] = data['ra']*15.
    
    TypeError: ufunc 'multiply' did not contain a loop with signature matching 
    types dtype('<U32') dtype('<U32') dtype('<U32')
    

    怎么回事??

    3 回复  |  直到 7 年前
        1
  •  3
  •   nudomarinero    7 年前

    正如您在html文件中看到的,应该有918行,但您得到919行。具有单位定义的行被读取为第一个数据行,它会弄乱所有内容。这就是为什么第一个“ra”是“decimal hr”,而不是数字,列数据类型被推断为dtype='str10'。

    可以使用“data_start”参数放弃有问题的行:

    data = ascii.read("Ldwarf.html", 
                      format="html", 
                      encoding="ISO-8859-1", 
                      data_start=2)
    

    现在,输入类型被正确地推断出来了,您应该不会有任何问题将“ra”乘以15。

        2
  •  0
  •   anothernode David Joel Lukombo    7 年前

    上面说 dtype str10 .

    将其转换为64位实数:

    data['ra'] = data['ra'].astype(numpy.float64)
    
        3
  •  0
  •   David    7 年前

    我无法重现您的问题,但我编造的数据['ra']不包含数字类型。它看起来像一个unicode字符串。

    如果是这种情况,则可以通过在乘法之前显式指定类型来解决:

    data['ra']=浮点(data['ra'])

    编辑:确定,则它包含一个数组,因此需要以兼容的方式修改类型:

    data['ra']=np.asarray(data['ra'],dtype='float64')