artsin
artsin

Reputation: 1494

Numpy array - append named column

Numpy allows me do like this:

>>>data = np.genfromtxt(r'd:/temp/data.txt', delimiter = ',', names = True)
>>>data['Time']
array([ 1.,  2.,  3.])

How can I make array like this? I mean to write like:

data = np.array([])
data.append(name = 'Time', data = [1., 2., 3.])
data['Time']
array([ 1.,  2.,  3.])

Upvotes: 2

Views: 1753

Answers (3)

hpaulj
hpaulj

Reputation: 231415

np.core.records has some nice functions for creating and manipulating structured arrays, but it is also good to know how to construct such arrays from scratch.

Your genfromtxt has read from a file with a simple column of string values. I can recreate it with a list of strings:

In [16]: data=np.genfromtxt(['Time','1.','2.','3.'],delimiter=',',names=True)

In [17]: data
Out[17]: 
array([(1.0,), (2.0,), (3.0,)], 
      dtype=[('Time', '<f8')])

In [18]: data['Time']
Out[18]: array([ 1.,  2.,  3.])

In [19]: data.dtype
Out[19]: dtype([('Time', '<f8')])

The key is the dtype which is derived from the header, and the appearance of the data. I'd suggest looking at the dtype from more complex csv files.

There are various ways of creating a dtype from scratch. One that recreates this case is dt = np.dtype([('Time',float)]).

A good way of constructing a similar array is with np.zeros (or np.empty), specifying the size and the same dtype. Once you have created the array, you can fill in the values field by field.

In [20]: data2=np.zeros(3,dtype=data.dtype)

In [21]: data2['Time']=[1,2,3]

Another way of creating a structured array is with np.array. The key is that the data has to be provided as a list of tuples.

In [22]: data1=np.array([(1,),(2,),(3,)],dtype=data.dtype)

Looking at the code for np.core.records.fromrecords shows a couple of other ways.

In the most general case if fills in the array row by row:

In [26]: data3=np.zeros(3,dtype=data.dtype)    
In [27]: for i,v in enumerate([1,2,3]):
   ....:     data3[i]=(v,)

And if the fields have all the same dtype, you can just view a 2d array with the new dtype.

In [29]: np.array([1.,2.,3.]).view(data.dtype)

Upvotes: 0

SylM
SylM

Reputation: 68

Like this ?

data = numpy.array([(1,), (2,), (3,)], dtype=[('Time', float)])

See also this usefull module to manipulate Record Array

Upvotes: 0

Anand S Kumar
Anand S Kumar

Reputation: 90929

You are trying to create a Record Array/Structured Array, you can checkout numpy.core.records.fromrecords -

In [35]: data = np.core.records.fromrecords([[1.], [2.], [3.]],names=['Time'])

In [36]: data
Out[36]:
rec.array([(1.0,), (2.0,), (3.0,)],
      dtype=[('Time', '<f8')])

In [37]: data['Time']
Out[37]: array([ 1.,  2.,  3.])

Upvotes: 2

Related Questions