how to make a numpy recarray from column arrays

I have a pair of numpy arrays; here's a simple equivalent example:

t = np.linspace(0,1,100)
data = ((t % 0.1) * 50).astype(np.uint16)

I want these to be columns in a numpy recarray of dtype f8, i2. This is the only way I can seem to get what I want:

X = np.array(zip(t,data),dtype=[('t','f8'),('data','i2')])

But is it the right way if my data values are large? I want to minimize the unnecessary overhead of shifting around data.

This seems like it should be an easy problem but I can't find a good example.


This wrorks

rec = np.rec.fromarrays((t, data), dtype=[('t','f8'),('data','i2')])

if you don't like that, you could always go this route

arr = np.hstack((t[:, None], data[:, None])).astype(np.dtype([('t', 'f8'), ('data', 'i2')]))


For the sake of being more thorough, I added another method with some timings.

def method_1(t, data):
    return np.rec.fromarrays((t, data), dtype=[('t','f8'),('data','i2')])

def method_2(t, data):
    return np.r_[t, data].reshape((-1, 2)).astype(np.dtype([('t', 'f8'), ('data', 'i2')]))

def method_3(t, data):
    return np.hstack((t[:,None], data[:, None])).astype(np.dtype([('t', 'f8'), ('data', 'i2')]))

def method_4(t, data):
    return np.array(zip(t,data),dtype=[('t','f8'),('data','i2')])

%timeit method_1(t, data)
10000 loops, best of 3: 20.8 us per loop

%timeit method_2(t, data)
10000 loops, best of 3: 28.9 us per loop

%timeit method_3(t, data)
100000 loops, best of 3: 16.6 us per loop

%timeit method_4(t, data)
10000 loops, best of 3: 56.9 us per loop

Need Your Help

Create a database using T SQL on a specified location


How to create a database using T SQL script on a specified location? Let's say, I want to create a SQL server database on D:\temp\dbFolder. How to do this?

Calculate exact result of complex throw of two D30

python math statistics puzzle

Okay, this bugged me for several years, now. If you sucked in statistics and higher math at school, turn away, now. Too late.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.