Original Post from 2019-06-20
Sorry to come late to the partly, but I was looking at a problem of converting numpy.float64 to regular Python float only. I saw 3 ways of doing that:
npValue.item()
npValue.astype(float)
float(npValue)
Here are the relevant timings from IPython:
In [1]: import numpy as np
In [2]: aa = np.random.uniform(0, 1, 1000000)
In [3]: %timeit map(float, aa)
10 loops, best of 3: 117 ms per loop
In [4]: %timeit map(lambda x: x.astype(float), aa)
1 loop, best of 3: 780 ms per loop
In [5]: %timeit map(lambda x: x.item(), aa)
1 loop, best of 3: 475 ms per loop
It sounds like float(npValue) seems much faster.
Update from 2024-08-05
A tremendous thank you to Mateo de Mayo for pointing out that
- in a modern setting,
aa[0].astype(float) is of type numpy.float64, not float, so does not solve the original problem;
- all 3 solutions likely need a container wrapped around then, e.g.,
tuple(map(...)) or list(map(...)) if you want to store the results in a meaningful way.
Rerunning the other 2 options on a modern Windows laptop with the same settings (C Python 3.11.9 in IPython 8.23.0 with numpy 1.26.4, I get
In [8]: %timeit map(float, aa)
71.4 ns ± 1.53 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)
In [9]: %timeit map(lambda x: x.item(), aa)
119 ns ± 3.33 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)
Conclusions
So float() is still faster but with only 50% improvement, not a 200% one.