[英]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.