簡體   English   中英

如何從相應索引列表中更改 NumPy 結構化數組中特定數據類型記錄的數據類型? (Python)

[英]How to change the data types of specific data type records in a NumPy structured array from a list of corresponding indices? (Python)

我有 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 中所有字段的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)])     

元組列表是在 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')]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM