【问题标题】:Why converting numpy.ndarray to custom data type using numpy.ndarray.astype multiplies my data?为什么使用 numpy.ndarray.astype 将 numpy.ndarray 转换为自定义数据类型会使我的数据相乘?
【发布时间】:2015-02-26 07:10:22
【问题描述】:

执行此代码:

import numpy as np

py_list = [2013, 8, 0.6552562894775783]
custom_type = np.dtype([
                        ('YEAR',np.uint16),
                        ('DOY', np.uint16),
                        ('REF',np.float16)
                        ])

NumPy_array = np.array(py_list)
NumPy_array_converted = NumPy_array.astype(custom_type)

print 'custom_type is:'
print custom_type
print '---------------------------------------------'
print 'py_list is:'
print py_list
print '---------------------------------------------'
print 'NumPy_array is:'
print NumPy_array
print '---------------------------------------------'
print 'NumPy_array converted to custom_type is:'
print NumPy_array_converted
print '---------------------------------------------'

打印:

custom_type is:
[('YEAR', '<u2'), ('DOY', '<u2'), ('REF', '<f2')]
---------------------------------------------
py_list is:
[2013, 8, 0.6552562894775783]
---------------------------------------------
NumPy_array is:
[  2.01300000e+03   8.00000000e+00   6.55256289e-01]
---------------------------------------------
NumPy_array converted to custom_type is:
[(2013, 2013, 2013.0) (8, 8, 8.0) (0, 0, 0.6552734375)]
---------------------------------------------

1) 问题是为什么在转换为自定义数据类型后,与未转换的 numpy 数组 NumPy_array 相比,我的数据增加了三倍 NumPy_array_converted

2) 如何更改custom_type 以获得不三倍数组?

【问题讨论】:

    标签: python arrays numpy type-conversion custom-data-type


    【解决方案1】:
    np.array([tuple(py_list)], custom_type)
    

    生产

    array([(2013, 8, 0.6552734375)], 
      dtype=[('YEAR', '<u2'), ('DOY', '<u2'), ('REF', '<f2')])
    

    结构化数组的数据应该是一个元组列表(或只是一个元组)。注意值的显示方式。 [(...)].

    astype 可能有办法做到这一点,但这很棘手。

    另外,请注意 NumPy_array 是 3 个浮点数,而 py_list 是 2 个整数和一个浮点数。 custom_type 想要将这 2 个整数转换为 'u2'。它们不兼容。

    【讨论】:

    • 这 2 个整数是年份(值 1900 - 2100)和一年中的某一天(值 1 - 366),因此“u2”对它们来说是可以的。
    • 你的方法效果很好。但我的列表中有圆括号:[(2013, 8, 0.6552734375)] 我能以某种方式摆脱它们吗?
    • 为什么要摆脱它们?这就是 numpy 如何显示像您这样的自定义类型。将其视为记录。
    • 浮点数与u2 - 4 bytes v 2 不兼容。
    • 因为它为我的数组提供了更多维度。要访问NumPy_array 值,我可以写NumPy_array[0]。要使用圆括号访问 NumPy_array_converted 中的相同值,我必须再写一个方括号 NumPy_array_converted[0][0]
    猜你喜欢
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    • 1970-01-01
    相关资源
    最近更新 更多