How do i control the sequence of records in a bar

2019-08-08 02:27发布

问题:

I have a data file that consists of several data points, that i would like to plot in a particular order. Here is the example data file:

cop   94.0528    313     441
cpr   225.172    726     747
ent   444.786    926     939
fsh   256.038    743     754
fsp   43.7764    340     356
pbp   343.708    825     834
rho   426.497    858     886
sca   342.431    427     872

I am currently plotting those just below each other in the way i set the example. How can i change the order of those data records within my python script to a specified order? I already tried to work this into an array. in this question here: How do i control the sequence of records in a bar plot with matplotlib?

So the next question i have from here on out is, can i do the exact same thing, but using a text-based sorting aaray?

So what i would put in would be something like this:

posarray = (crp, 2), (cop,1)

edit: The posarray would denote the position of the record with the text in posarray[0] in the outputarray. The crp would end up at the second position, cop at the first and so on.

and what it would give me would be

cop   94.0528    313     441
cpr   225.172    726     747

the best thing would be using some kind of insert, so that if i forget to mention an item in the sorting array it would sink to the bottom.

回答1:

As described in the answer to your previous question, you can achieve what you want with some indexing trick.

Let's assume that you have a numpy representation of your array as such:

a = array([('cop', 94.0528, 313, 441), ('cpr', 225.172, 726, 747),
           ('ent', 444.786, 926, 939), ('fsh', 256.038, 743, 754),
           ('fsp', 43.7764, 340, 356), ('pbp', 343.708, 825, 834),
           ('rho', 426.497, 858, 886), ('sca', 342.431, 427, 872)], 
          dtype=[('f0', '|S3'), ('f1', '<f8'), ('f2', '<i8'), ('f3', '<i8')])

You can easily get a list of your first column:

>>> fields = list(a['f0'])

Now, define a list of the fields ordered as you want, for example:

>>> new_order = ['cpr', 'cop', 'ent', 'fsh', 'fsp', 'rho', 'pbp', 'sca']

You can get the position of each item of new_order in your fields list by using the index method and some list comprehension:

>>> indices = [fields.index(i) for i in new_order]
[1, 0, 2, 3, 4, 6, 5, 7]

(You can understand why we needed fields to be a list, as an array doesn't have a index method)

That's it. You can now reorder your array with the indices list:

>>> a[indices]
array([('cpr', 225.172, 726, 747), ('cop', 94.0528, 313, 441),
       ('ent', 444.786, 926, 939), ('fsh', 256.038, 743, 754),
       ('fsp', 43.7764, 340, 356), ('rho', 426.497, 858, 886),
       ('pbp', 343.708, 825, 834), ('sca', 342.431, 427, 872)], 
      dtype=[('f0', '|S3'), ('f1', '<f8'), ('f2', '<i8'), ('f3', '<i8')])