【问题标题】:How to change the data types of specific data type records in a NumPy structured array from a list of corresponding indices? (Python)如何从相应索引列表中更改 NumPy 结构化数组中特定数据类型记录的数据类型? (Python)
【发布时间】:2021-08-13 08:48:30
【问题描述】:

我有 NumPy 结构化数组data

data_tup = [tuple(ele) for ele in array]
data = np.array(
    data_tup, 
    dtype = [("field_1", "<U30"), ("field_2", "<U30"),
             ("field_3", "<U30"), ("field_4", "<U30"),
             ("field_5", "<U30"), ("field_6", "<U30"), 
             ("field_7", "<U30"), ("field_8", "<U30"), 
             ("field_9", "<U30")])       

我想将data 中所有字段的数据类型更改为float,但列表indices 指定的字段除外,该列表包含dtype 中字段的索引值,不应更改数据类型.

例如:

indices = [0, 4, 5, 7]
data = np.array(
data_tup, 
dtype = [("field_1", "<U30"), ("field_2", "<U30"),
         ("field_3", "<U30"), ("field_4", "<U30"),
         ("field_5", "<U30"), ("field_6", "<U30"), 
         ("field_7", "<U30"), ("field_8", "<U30"), 
         ("field_9", "<U30")])     

data 中的新 dtype 现在应该是:

 dtype = [("field_1", "<U30"), ("field_2", float),
         ("field_3", float), ("field_4", float),
         ("field_5", "<U30"), ("field_6", "<U30"), 
         ("field_7", float), ("field_8", "<U30"), 
         ("field_9", float)])     

【问题讨论】:

    标签: python list numpy tuples structured-array


    【解决方案1】:

    元组列表是在 dtype 之间进行转换的最简单方法,如下所示:

    In [63]: data = [('123','456')]
    In [64]: np.array(data, dtype='U10,U10')
    Out[64]: array([('123', '456')], dtype=[('f0', '<U10'), ('f1', '<U10')])
    In [65]: np.array(data, dtype='U10,float')
    Out[65]: array([('123', 456.)], dtype=[('f0', '<U10'), ('f1', '<f8')])
    

    如果从全字符串 dtype 数组开始:

    In [77]: np.array(data, dtype='U10,U10').tolist()
    Out[77]: [('123', '456')]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-20
      • 2018-05-25
      相关资源
      最近更新 更多