numpy, h5py: How do I make an array sorted by one of its columns from a bigger one saved with h5py?

StackOverflow https://stackoverflow.com/questions/19704880

I'd like to give you some background info so you understand my problem better.

From the results of an experiment I fill a big hdf5 table with lots of columns using h5py. Once all my measurements are done, I need to plot and fit some results. This is already working but when I get to the point when I want to plot the fitting function, as my data is not sorted by the column with the 'x' axis data, instead of a single line I get an ugly back-and-forth line (I'd show it to you but I don't have enough reputation yet).

So my first thought was to sort the arrays before plotting and fitting. I tried following several guides I found here but my joined array had the wrong shape and that was the time I though there might be a better way of doing it.

So my question is, What's the best way of getting an array sorted by one of its columns from a bigger array saved in an hdf5 file using h5py?

This is how I'm currently doing it:

Let's say I already extracted the columns from the hdf5 file (even though maybe this could be improved!), now I'm making them up.

x_d = array([5, 2, 10, 4])
y_d = array([0.2, 1.0, 4.1, 0.1])

wtype = np.dtype([('x', x_d.dtype), ('y', y_d.dtype)])
w = np.empty(len(x_d), dtype=wtype)
w['x'] = x_d
w['y'] = y_d

w.sort(order='x')
有帮助吗?

解决方案

Something along these lines should work:

f = h5py.File('myfile.hdf5','r')
x_d = f['x_axis'][:]
y_d = f['values'][:]
sorted_y = y_d[numpy.argsort(x_d)]

or if you want to have the reverse order:

sorted_y = y_d[numpy.argsort(x_d)[::-1]]
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top