Hey guys,

I have a simple numpy datatype:

spec_dtype = np.dtype([
	     ('wavelength', float),
   	     ('intensity', float)
			])

I chose to use this in my program because it's very easy to read in 2-column spectral data files using the genfromtxt() method. Therefore, I made a fairly sizable program around this datatype. Now I'm running into a situation wherein I need to pass internal data lists for the "wavelength" and "intensity", rather them importing them externally from a file. This is giving me headaches with manual array creation.

Imagine I have a list of wavelengths and intensity variables pre-stored in my program. For example:

wavelengths=[300.00, 200.00, 100.00]
intensities=[23, 32, 43]

I'd like to simply put these into an array of spec dtype. At first I tried:

myarray=np.array([(wavelengths),(intensities)], dtype=spec_dtype)

This actually doesn't produce the type of array that I'd expect. Instead, I had to iterate through the array and append the items one by one. For example:

myarray=np.empty(,dtype=spec_dtype)
for i in range(len(wavelengths)):
    mydata[i]=((wavelengths[i]), (intensities[i]))

Is there anyway to avoid this and do it all in one fell swoop?

Thanks.

How about simply ziping the lists together:

import numpy as np

spec_dtype = np.dtype([
	     ('wavelength', float),
   	     ('intensity', float)
			])

wavelengths=[300.00, 200.00, 100.00]
intensities=[23, 32, 43]

mydata = np.array(zip(wavelengths, intensities), dtype=spec_dtype)

print(mydata)

Ahh you're a total genius! Thanks. I didn't even realize this zip feature existed!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.