numpy改变数组类型的方法

使用astype函数转换dtype

import numpy as np
a = np.zeros([2,2],dtype='float32')
print("a type is {}".format(a.dtype))

b = a.astype(int)
print("b is type {}".format(b.dtype))

b = a.astype(np.float32)
print("b is type {}".format(b.dtype))

numpy.ndarray.astype输入的类型有两种字符str或者dtype

numpy.ndarray.astype
ndarray.astype(**dtype**, order='K', casting='unsafe', subok=True, copy=True)
Copy of the array, cast to a specified type.

Parameters:	
dtype : **str or dtype**

Typecode or data-type to which the array is cast.

numpy中np.array()与np.asarray的区别以及.tolist

array和asarray都可以将结构数据转化为ndarray,但是主要区别就是当数据源是ndarray时,array仍然会copy出一个副本,占用新的内存,但asarray不会。

  • list列表转化成ndarray的数组
import numpy as np
a = [[1,2],[4,6]]
b = np.array(a,dtype=np.float32)
print(b.dtype)
  • .tolist将array类型转为list类型
import numpy as np
a = [[1,2],[4,6]]
b = np.array(a,dtype=np.float32)
print(b.dtype)

b.tolist()

猜你喜欢

转载自blog.csdn.net/weixin_37707670/article/details/118967672