如何在不改变其维度的情况下将名称添加到 numpy 数组?

Jos*_*ien 7 python arrays numpy

我有一个现有的两列 numpy 数组,我需要向其中添加列名。在下面的块 1dtype显示的玩具示例中传递那些通过工作。但是,对于我的实际数组,如Block 2所示,相同的方法会产生意外(对我而言!)更改数组维度的副作用。

如何将我的实际数组(在Y下面第二个块中命名的数组)转换为具有命名列的数组,就像我A在第一个块中为数组所做的那样?

第 1 块:(A未重塑维度的已命名列)

import numpy as np
A = np.array(((1,2),(3,4),(50,100)))
A
# array([[  1,   2],
#        [  3,   4],
#        [ 50, 100]])
dt = {'names':['ID', 'Ring'], 'formats':[np.int32, np.int32]}
A.dtype=dt
A
# array([[(1, 2)],
#        [(3, 4)],
#        [(50, 100)]], 
#       dtype=[('ID', '<i4'), ('Ring', '<i4')])
Run Code Online (Sandbox Code Playgroud)

第 2 块:(命名我的实际数组的列Y,重塑其维度)

import numpy as np
## Code to reproduce Y, the array I'm actually dealing with
nRings = 3
nn = [[nRings+1-n] * n for n in range(nRings+1)]
RING = reduce(lambda x, y: x+y, nn)
ID = range(1,len(RING)+1)
X = numpy.array([ID, RING])
Y = X.T
Y
# array([[1, 3],
#        [2, 2],
#        [3, 2],
#        [4, 1],
#        [5, 1],
#        [6, 1]])

## My unsuccessful attempt to add names to the array's columns    
dt = {'names':['ID', 'Ring'], 'formats':[np.int32, np.int32]}
Y.dtype=dt
Y
# array([[(1, 2), (3, 2)],
#        [(3, 4), (2, 1)],
#        [(5, 6), (1, 1)]], 
#       dtype=[('ID', '<i4'), ('Ring', '<i4')])

## What I'd like instead of the results shown just above
# array([[(1, 3)],
#        [(2, 2)],
#        [(3, 2)],
#        [(4, 1)],
#        [(5, 1)],
#        [(6, 1)]],
#       dtype=[('ID', '<i4'), ('Ring', '<i4')])
Run Code Online (Sandbox Code Playgroud)

lX-*_*-Xl 7

store- different-datatypes-in-one-numpy-array 另一个页面包括一个很好的解决方案,将名称添加到可以用作列的数组示例:

r = np.core.records.fromarrays([x1,x2,x3],names='a,b,c')
# x1, x2, x3 are flatten array
# a,b,c are field name
Run Code Online (Sandbox Code Playgroud)


Bi *_*ico 5

首先,因为您的问题是关于为数组命名,我觉得有必要指出,使用“结构化数组”来命名可能不是最好的方法。当我们处理表格时,我们经常喜欢给行/列命名,如果是这种情况,我建议你尝试像Pandas这样很棒的东西。如果你只是想在你的代码中组织一些数据,数组字典通常比结构化数组好得多,例如你可以这样做:

Y = {'ID':X[0], 'Ring':X[1]}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,如果你想使用结构化数组,我认为这是最清晰的方法:

import numpy as np

nRings = 3
nn = [[nRings+1-n] * n for n in range(nRings+1)]
RING = reduce(lambda x, y: x+y, nn)
ID = range(1,len(RING)+1)
X = np.array([ID, RING])

dt = {'names':['ID', 'Ring'], 'formats':[np.int, np.int]}
Y = np.zeros(len(RING), dtype=dt)
Y['ID'] = X[0]
Y['Ring'] = X[1]
Run Code Online (Sandbox Code Playgroud)