Home > Software engineering >  how to find records starting with a particular letter in numpy array
how to find records starting with a particular letter in numpy array

Time:04-05

i am beginner in numpy and created the following array

data=np.array([("abcd",111,9666),("atchd",222,6669),("cdef",444,8756)],dtype=[("name",str,10),("roll",int),("phone",int)])
print(data[data["name"][0]=='a']["name"])

I am trying to print records that have name property starting with character 'a' but this is returning empty array. pl update

CodePudding user response:

The problem is, that you can not index the "string-axis" of your data, since it is not part of the numpy array. To achieve the behaviour you expect, you can utilize np.char.startswith :

import numpy as np
data=np.array(
  [
    ("abcd",111,9666),
    ("atchd",222,6669),
    ("cdef",444,8756)
  ],
  dtype=[
    ("name",str,10),("roll",int),("phone",int)
  ]
)
print(data[np.char.startswith(data["name"], 'a')]["name"])
# ['abcd' 'atchd']

Note that there are also other string operations supported by numpy.

  • Related