How to add names to a numpy array without changing its dimension?
First because your question asks about giving names to arrays, I feel obligated to point out that using "structured arrays" for the purpose of giving names is probably not the best approach. We often like to give names to rows/columns when we're working with tables, if this is the case I suggest you try something like pandas which is awesome. If you simply want to organize some data in your code, a dictionary of arrays is often much better than a structured array, so for example you can do:
Y = {'ID':X[0], 'Ring':X[1]}
With that out of the way, if you want to use a structured array, here is the clearest way to do it in my opinion:
import numpy as npnRings = 3nn = [[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]
store-different-datatypes-in-one-numpy-arrayanother page including a nice solution of adding name to an array which can be used as columnExample:
r = np.core.records.fromarrays([x1,x2,x3],names='a,b,c')# x1, x2, x3 are flatten array# a,b,c are field name
This is because Y is not C_CONTIGUOUS, you can check it by Y.flags
:
C_CONTIGUOUS : False F_CONTIGUOUS : True OWNDATA : False WRITEABLE : True ALIGNED : True UPDATEIFCOPY : False
You can call Y.copy()
or Y.ravel()
first:
dt = {'names':['ID', 'Ring'], 'formats':[np.int32, np.int32]}print Y.ravel().view(dt) # the result shape is (6, )print Y.copy().view(dt) # the result shape is (6, 1)