[SciPy-User] equivalent of tolist().index(entry) for numpy 1d array of strings
Mon Dec 21 22:39:11 CST 2009
On Mon, Dec 21, 2009 at 9:09 PM, Ryan Krauss <firstname.lastname@example.org> wrote:
> I am still open to more elegant solutions, but it seems like my
> concerns about .tolist() being inefficient are unfounded (this may be
> an indicator that I don't understand the inner workings of numpy very
> Here is my test:
> t1 = time.time()
> index1 = where(self.md5sum==photo.md5sum)
"where" finds all matching elements, there is no early stopping. I
think there was a similar argument recently that python is faster if
early stopping/return is desired.
> t2 = time.time()
> index2 = mysearch(self.md5sum, photo.md5sum)
> t3 = time.time()
> index3 = self.md5sum.tolist().index(photo.md5sum)
index finds only the first match, and then can return immediately.
I guess, if you only care about the first element that matches the
condition, then python might always be faster than numpy. The
advantage of "where" would be, if you need to do something with all
elements that match, e.g. replace them with something else.
> t4 = time.time()
> All 3 approaches lead to the same result. Here are my timing results:
> def mysearch(arrayin, element):
> bool_vect = where(arrayin==element)
> assert(len(bool_vect)==1), 'Did not find exactly 1 match for ' +
> return bool_vect
> Now, for this test, the arrays didn't have very many elements (10 ish).
> On Mon, Dec 21, 2009 at 7:53 PM, Ryan Krauss <email@example.com> wrote:
>> I wrote some code to work with csv spreadsheet files by reading the
>> columns into lists, but I need to rework the code to work with numpy
>> 1d arrays of strings rather than lists. I need to search one of these
>> columns/arrays. What is the best way to find the index for the
>> element that matches a certain string (or maybe just the first element
>> to match such a string)?
>> With the columns as lists, I was doing
>> index = mylist.index(entry)
>> So, I could obviously do
>> index = mylist.tolist().index(entry)
>> but I don't know if that would be slower or clumsier than something like
>> bool_vect = where(mylist==entry)
>> index = bool_vect
>> or just
>> index = where(mylist==entry)
>> Any thoughts? Is there an easier way?
> SciPy-User mailing list
More information about the SciPy-User