2 回答

TA貢獻1772條經驗 獲得超6個贊
In [128]: array = np.array([(1,2,3,4), (5,6,7,8)],dtype=[('a', 'i4'), ('b', 'i4'), ('c', '
...: i4'),('d', 'i4')])
...: names = list(array.dtype.names)
...: new_names=names[1:]
...: data = array[new_names]
In [129]: array.dtype
Out[129]: dtype([('a', '<i4'), ('b', '<i4'), ('c', '<i4'), ('d', '<i4')])
In [130]: names
Out[130]: ['a', 'b', 'c', 'd']
In [131]: data
Out[131]:
array([(2, 3, 4), (6, 7, 8)],
dtype={'names':['b','c','d'], 'formats':['<i4','<i4','<i4'], 'offsets':[4,8,12], 'itemsize':16})
請注意,data.dtype有offsets. 在最新numpy版本中,選擇字段的子集會生成view. array['a']還在那里,只是'隱藏'。
除了這一變化,他們還為以下內容添加了一些功能recfunctions:
In [133]: import numpy.lib.recfunctions as rf
要制作沒有“a”數據的副本:
In [134]: data1 = rf.repack_fields(data)
In [135]: data1
Out[135]:
array([(2, 3, 4), (6, 7, 8)],
dtype=[('b', '<i4'), ('c', '<i4'), ('d', '<i4')])
并制作一個非結構化數組:
In [136]: rf.structured_to_unstructured(array)
Out[136]:
array([[1, 2, 3, 4],
[5, 6, 7, 8]], dtype=int32)
In [137]: rf.structured_to_unstructured(data)
Out[137]:
array([[2, 3, 4],
[6, 7, 8]], dtype=int32)
In [138]: rf.structured_to_unstructured(data1)
Out[138]:
array([[2, 3, 4],
[6, 7, 8]], dtype=int32)
這些功能記錄在:
https://docs.scipy.org/doc/numpy/user/basics.rec.html#accessing-multiple-fields
由于所有字段都具有相同的 dtype ('i4')view作品 - 在一定程度上
In [142]: data.view('i4')
Out[142]: array([1, 2, 3, 4, 5, 6, 7, 8], dtype=int32)
In [143]: data1.view('i4')
Out[143]: array([2, 3, 4, 6, 7, 8], dtype=int32)
但它是基礎數據的視圖,形狀混亂。早期版本中存在此形狀問題。所以最好閱讀這些變化,并使用推薦的功能。
在之前的 SO 問題中,我可能建議使用列表作為中介:
In [144]: data.tolist()
Out[144]: [(2, 3, 4), (6, 7, 8)]
In [145]: np.array(data.tolist())
Out[145]:
array([[2, 3, 4],
[6, 7, 8]])

TA貢獻1831條經驗 獲得超9個贊
嘗試在最后切片:
new_array = data.view('i4').reshape(len(data),-1)[:,1:]
結果:
[[2 3 4]
[6 7 8]]
添加回答
舉報