【數據分析】Numpy及數組創建,數據類型,形狀和計算 No.3

一、Numpy

Python中做科學計算的基礎庫,重在數值計算,多用於處理大型多維數組上的數值運算。

特點:快速、方便、科學計算的基礎庫

安裝:pip install numpy

二、numpy創建數組(矩陣)

import numpy as np

def nu():

    a = np.array([1,2,3,4,5])
    print (a)
    b = np.array(range(0,6))
    print (b)

    print("class: %s " % str(type(a)))
    print("type: %s " % a.dtype)

    return None


if __name__ == "__main__":
    nu()

執行結果:

F:\Python\3.7\python.exe E:/PythonProject/Scripts/data_analysis.py

[1 2 3 4 5]

[0 1 2 3 4 5]

class: <class 'numpy.ndarray'>

type: int32

三、Numpy中更多數據類型

d = np.array(range(0,10), dtype="float")
print(d)
print("type: %s " % d.dtype)

t = np.array([1,0,2,3,0], dtype=bool)
print(t)
print("type: %s " % t.dtype)

e =d.astype('i1')
print(e)
print("type: %s " % e.dtype)


f = round(random.random(),2)
print(f)

結果:

[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
type: float64 
[ True False  True  True False]
type: bool 
[0 1 2 3 4 5 6 7 8 9]
type: int8 
0.75

四、數組的形狀

import numpy as np
t = np.arange(12)
print (t)
print (t.shape)

t1 = np.array([[1,2,3,4],[5,6,7,8]])
print (t1.shape)
print(t1.reshape(4,2))
print(t1.shape)
print(t1.reshape(4, 2).shape)

執行結果:

[ 0  1  2  3  4  5  6  7  8  9 10 11]
(12,)
(2, 4)
[[1 2]
 [3 4]
 [5 6]
 [7 8]]
(2, 4)
(4, 2)

 

五、數組和數,數組的計算

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章