0

I have a numpy structured array e.g. B which has the following form

array([('J0006+1834', '-99', 0.693748, 2.1e-15),
   ('J0007+7303', 'NRAD', 0.315873, 3.6e-13),
   ('B0011+47', '-99', 1.240699, 5.64e-16), ...,
   ('B2334+61', '-99', 0.49537, 1.93e-13),
   ('J2346-0609', '-99', 1.181463, 1.36e-15),
   ('B2351+61', '-99', 0.944784, 1.63e-14)], 
  dtype=[('Name', 'S10'), ('Type', 'S10'), ('P0', '<f8'), ('P1', '<f8')])

I need to be able to search for partial matches of the second column named Type. My array contains values in the secong columns that start with NR and I would like to be able to search for them as a group. I tried np.where and startwidth but I was not successfull. I also tried with wildcards but nothing worked.

Ideally I would like a command like this

B[B['Type']=='NR*']

which would return alla the elements of the array which in th column Type start with NR.

Thank you for your time and I am looking forward for your replies.

1 Answer 1

1

If you really want to use numpy, you could use np.char.startswith:

>>> np.char.startswith(d["Type"], "NR")
array([False,  True, False, False, False, False], dtype=bool)
>>> d[np.char.startswith(d["Type"], "NR")]
array([('J0007+7303', 'NRAD', 0.315873, 3.6e-13)], 
      dtype=[('Name', 'S10'), ('Type', 'S10'), ('P0', '<f8'), ('P1', '<f8')])

But IMHO this is really more of a pandas problem:

>>> df = pd.DataFrame(d)
>>> df
         Name  Type        P0            P1
0  J0006+1834   -99  0.693748  2.100000e-15
1  J0007+7303  NRAD  0.315873  3.600000e-13
2    B0011+47   -99  1.240699  5.640000e-16
3    B2334+61   -99  0.495370  1.930000e-13
4  J2346-0609   -99  1.181463  1.360000e-15
5    B2351+61   -99  0.944784  1.630000e-14
>>> df[df.Type.str.startswith("NR")]
         Name  Type        P0            P1
1  J0007+7303  NRAD  0.315873  3.600000e-13

Admittedly here the syntax is similar enough that there's not much of an advantage either way, but once you want to start performing other operations like grouping, pandas starts to shine and using bare numpy becomes increasingly inconvenient.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.