I've compared a few of the methods possible for doing this, including pandas, several numpy methods, and a list comprehension method.
First, let's start with a baseline:
>>> import numpy as np
>>> import operator
>>> import pandas as pd
>>> x = [1, 2, 1, 2]
>>> %time count = np.sum(np.equal(1, x))
>>> print("Count {} using numpy equal with ints".format(count))
CPU times: user 52 µs, sys: 0 ns, total: 52 µs
Wall time: 56 µs
Count 2 using numpy equal with ints
So, our baseline is that the count should be correct 2
, and we should take about 50 us
.
Now, we try the naive method:
>>> x = ['s', 'b', 's', 'b']
>>> %time count = np.sum(np.equal('s', x))
>>> print("Count {} using numpy equal".format(count))
CPU times: user 145 µs, sys: 24 µs, total: 169 µs
Wall time: 158 µs
Count NotImplemented using numpy equal
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/ipykernel_launcher.py:1: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
"""Entry point for launching an IPython kernel.
And here, we get the wrong answer (NotImplemented != 2
), it takes us a long time, and it throws the warning.
So we'll try another naive method:
>>> %time count = np.sum(x == 's')
>>> print("Count {} using ==".format(count))
CPU times: user 46 µs, sys: 1 µs, total: 47 µs
Wall time: 50.1 µs
Count 0 using ==
Again, the wrong answer (0 != 2
). This is even more insidious because there's no subsequent warnings (0
can be passed around just like 2
).
Now, let's try a list comprehension:
>>> %time count = np.sum([operator.eq(_x, 's') for _x in x])
>>> print("Count {} using list comprehension".format(count))
CPU times: user 55 µs, sys: 1 µs, total: 56 µs
Wall time: 60.3 µs
Count 2 using list comprehension
We get the right answer here, and it's pretty fast!
Another possibility, pandas
:
>>> y = pd.Series(x)
>>> %time count = np.sum(y == 's')
>>> print("Count {} using pandas ==".format(count))
CPU times: user 453 µs, sys: 31 µs, total: 484 µs
Wall time: 463 µs
Count 2 using pandas ==
Slow, but correct!
And finally, the option I'm going to use: casting the numpy
array to the object
type:
>>> x = np.array(['s', 'b', 's', 'b']).astype(object)
>>> %time count = np.sum(np.equal('s', x))
>>> print("Count {} using numpy equal".format(count))
CPU times: user 50 µs, sys: 1 µs, total: 51 µs
Wall time: 55.1 µs
Count 2 using numpy equal
Fast and correct!
thing
(which may or may not be a numpy type; I don't know) and I want to see ifthing == 'some string'
and get a simplebool
result, what should I do?np.atleast_1d(thing)[0] == 'some string'
? But that's not robust to some joker putting'some string'
in the first element of an array. I guess I have to test the type ofthing
first and then only do the==
test if it's a string (or not a numpy object).