将numpy.float64列表转换为Python中的float

Joh*_*ast 8 numpy type-conversion python-3.x

将numpy.float64类型的元素列表转换为float类型的最快方法是什么?我目前正在使用简单的for loop迭代float().

我遇到过这篇文章:将numpy dtypes转换为本机python类型,但我的问题不是如何在python中转换类型,而是更具体地说,如何以最快的方式将一种类型的整个列表转换为另一种类型. python(即在这个特定情况下numpy.float64浮动).我希望有一些秘密的python机器,我没有遇到过它可以一次完成所有这一切:)

War*_*ser 11

tolist()方法应该做你想要的.如果你有一个numpy数组,只需调用tolist():

In [17]: a
Out[17]: 
array([ 0.        ,  0.14285714,  0.28571429,  0.42857143,  0.57142857,
        0.71428571,  0.85714286,  1.        ,  1.14285714,  1.28571429,
        1.42857143,  1.57142857,  1.71428571,  1.85714286,  2.        ])

In [18]: a.dtype
Out[18]: dtype('float64')

In [19]: b = a.tolist()

In [20]: b
Out[20]: 
[0.0,
 0.14285714285714285,
 0.2857142857142857,
 0.42857142857142855,
 0.5714285714285714,
 0.7142857142857142,
 0.8571428571428571,
 1.0,
 1.1428571428571428,
 1.2857142857142856,
 1.4285714285714284,
 1.5714285714285714,
 1.7142857142857142,
 1.857142857142857,
 2.0]

In [21]: type(b)
Out[21]: list

In [22]: type(b[0])
Out[22]: float
Run Code Online (Sandbox Code Playgroud)

实际上,如果你真的有numpy.float64对象的python列表,那么@ Alexander的答案很棒,或者你可以将列表转换为数组然后使用该tolist()方法.例如

In [46]: c
Out[46]: 
[0.0,
 0.33333333333333331,
 0.66666666666666663,
 1.0,
 1.3333333333333333,
 1.6666666666666665,
 2.0]

In [47]: type(c)
Out[47]: list

In [48]: type(c[0])
Out[48]: numpy.float64
Run Code Online (Sandbox Code Playgroud)

@亚历山大的建议,列表理解:

In [49]: [float(v) for v in c]
Out[49]: 
[0.0,
 0.3333333333333333,
 0.6666666666666666,
 1.0,
 1.3333333333333333,
 1.6666666666666665,
 2.0]
Run Code Online (Sandbox Code Playgroud)

或者,转换为数组然后使用该tolist()方法.

In [50]: np.array(c).tolist()
Out[50]: 
[0.0,
 0.3333333333333333,
 0.6666666666666666,
 1.0,
 1.3333333333333333,
 1.6666666666666665,
 2.0]
Run Code Online (Sandbox Code Playgroud)

如果你关心速度,这里是一个比较.输入,x是numpy.float64对象的python列表:

In [8]: type(x)
Out[8]: list

In [9]: len(x)
Out[9]: 1000

In [10]: type(x[0])
Out[10]: numpy.float64
Run Code Online (Sandbox Code Playgroud)

列表理解的时间:

In [11]: %timeit list1 = [float(v) for v in x]
10000 loops, best of 3: 109 µs per loop
Run Code Online (Sandbox Code Playgroud)

转换为numpy数组的时间然后tolist():

In [12]: %timeit list2 = np.array(x).tolist()
10000 loops, best of 3: 70.5 µs per loop
Run Code Online (Sandbox Code Playgroud)

因此,将列表转换为数组然后调用会更快tolist().


Ale*_*der 5

你可以使用列表理解:

floats = [float(np_float) for np_float in np_float_list]
Run Code Online (Sandbox Code Playgroud)