numpy數據類型dtype轉換

 

這篇文章咱們玩玩numpy的數值數據類型轉換數組

 

導入numpy

>>> import numpy as np

 

1、隨便玩玩

生成一個浮點數組

>>> a = np.random.random(4)


看看信息

>>> a
array([ 0.0945377 ,  0.52199916,  0.62490646,  0.21260126])
>>> a.dtype
dtype('float64')
>>> a.shape
(4,)

 

改變dtype,發現數組長度翻倍!

>>> a.dtype = 'float32'
>>> a
array([  3.65532693e+20,   1.43907535e+00,  -3.31994873e-25,
         1.75549972e+00,  -2.75686653e+14,   1.78122652e+00,
        -1.03207532e-19,   1.58760118e+00], dtype=float32)
>>> a.shape
(8,)


改變dtype,數組長度再次翻倍!

>>> a.dtype = 'float16'
>>> a
array([ -9.58442688e-05,   7.19000000e+02,   2.38159180e-01,
         1.92968750e+00,              nan,  -1.66034698e-03,
        -2.63427734e-01,   1.96875000e+00,  -1.07519531e+00,
        -1.19625000e+02,              nan,   1.97167969e+00,
        -1.60156250e-01,  -7.76290894e-03,   4.07226562e-01,
         1.94824219e+00], dtype=float16)
>>> a.shape
(16,)


改變dtype='float',發現默認就是float64,長度也變回最初的4

>>> a.dtype = 'float'
>>> a
array([ 0.0945377 ,  0.52199916,  0.62490646,  0.21260126])
>>> a.shape
(4,)
>>> a.dtype
dtype('float64')


把a變爲整數,觀察其信息

>>> a.dtype = 'int64'
>>> a
array([4591476579734816328, 4602876970018897584, 4603803876586077261,
       4596827787908854048], dtype=int64)
>>> a.shape
(4,)


改變dtype,發現數組長度翻倍!

>>> a.dtype = 'int32'
>>> a
array([ 1637779016,  1069036447, -1764917584,  1071690807,  -679822259,
        1071906619, -1611419360,  1070282372])
>>> a.shape
(8,)


改變dtype,發現數組長度再次翻倍!

>>> a.dtype = 'int16'
>>> a
array([-31160,  24990,  13215,  16312,  32432, -26931, -19401,  16352,
       -17331, -10374,   -197,  16355, -20192, -24589,  13956,  16331], dtype=int16)
>>> a.shape
(16,)


改變dtype,發現數組長度再次翻倍!

>>> a.dtype = 'int8'
>>> a
array([  72, -122,  -98,   97,  -97,   51,  -72,   63,  -80,  126,  -51,
       -106,   55,  -76,  -32,   63,   77,  -68,  122,  -41,   59,   -1,
        -29,   63,   32,  -79,  -13,  -97, -124,   54,  -53,   63], dtype=int8)
>>> a.shape
(32,)


改變dtype,發現整數默認int32!

>>> a.dtype = 'int'
>>> a.dtype
dtype('int32')
>>> a
array([ 1637779016,  1069036447, -1764917584,  1071690807,  -679822259,
        1071906619, -1611419360,  1070282372])
>>> a.shape
(8,)

 

2、換一種玩法

不少時候咱們用numpy從文本文件讀取數據做爲numpy的數組,默認的dtype是float64。
可是有些場合咱們但願有些數據列做爲整數。若是直接改dtype='int'的話,就會出錯!緣由如上,數組長度翻倍了!!!dom


下面的場景假設咱們獲得了導入的數據。咱們的本意是但願它們是整數,但其實是倒是浮點數(float64)

>>> b = np.array([1., 2., 3., 4.])
>>> b.dtype
dtype('float64')

 

astype(int) 獲得整數,而且不改變數組長度

>>> c = b.astype(int)
>>> c
array([1, 2, 3, 4])
>>> c.shape
(8,)
>>> c.dtype dtype('int32')

 

若是直接改變b的dtype的話,b的長度翻倍了,這不是咱們想要的(固然若是你想的話)

>>> b
array([ 1.,  2.,  3.,  4.])

>>> b.dtype = 'int'
>>> b.dtype
dtype('int32')
>>> b
array([         0, 1072693248,          0, 1073741824,          0,
       1074266112,          0, 1074790400])
>>> b.shape
(8,)



3、結論

numpy中的數據類型轉換,不能直接改原數據的dtype!  只能用函數astype()

相關文章
相關標籤/搜索