[Numpy-discussion] ndarray from column data

Robert kxroberto at googlemail.com
Thu Jul 2 15:00:19 EDT 2009


Elaine Angelino wrote:
> Hi there --
> 
> Is there a fast way to make a numpy ndarray from column data? 
> 
> For example, suppose I want to make an ndarray with 2 rows and 3 columns 
> of different data types based on the following column data:
> 
> C0 = [1,2]
> C1 = ['a','b']
> C2 = [3.3,4.4]
> 
> I could create an empty ndarray and fill the columns one by one:
> 
> X = numpy.core.ndarray((2,), dtype='<i4,|S1,<f8')
> X['f0'] = C0
> X['f1'] = C1
> X['f2'] = C2
> 
> The result is the same as:
> 
> X = numpy.array([(1,'a',3.3), (2,'b',4.4)], dtype='<i4,|S1,<f8')
> 
> but I would like to make X directly from the column data.
> 
> [  I know that numpy.core.records.fromarrays will produce a numpy 
> recarray from column data, but this of course is a recarray and not a 
> ndarray! For ex:
> 
> X = numpy.numpy.core.records.fromarrays([C0,C1,C2])  ]
> 
> Thanks for any help,
> 
> Elaine
> 


 >>> np.array(zip(C0,C1,C2), dtype='<i4,|S1,<f8')
array([(1, 'a', 3.2999999999999998), (2, 'b', 4.4000000000000004)],
       dtype=[('f0', '<i4'), ('f1', '|S1'), ('f2', '<f8')])


Well, such thing is never a real 2D ndarray with real "columns" 
anyway, which you can access like X[row,col], but a 1D array of 
tuples.

for iso-type data -> 2D there is

 >>> np.column_stack((C0,C1,C2))
array([['1', 'a', '3.3'],
        ['2', 'b', '4.4']],
       dtype='|S8')



Robert








More information about the NumPy-Discussion mailing list