[Python_1: numpy]

Numpy 基本操作,持續更新...

 
1.導入numpy 包

import numpy as np

 

2.建立array 查看數據類型

x1 = np.array([1,2,3,4])
x1.dtype #查看類型,數值型


注意,當數據中混有多種數據類型時,會識別爲字符型:

x2 = np.array([
             [1,2,3,'4'],
             [2,3,4,5]
              ])
x2.dtype #result dtype('<U11')

3.np.array 的索引

print(x2[0,3]) #索引,第0行第4列
print(x2[:,1:3]) #索引,取第一列和第二列

vector = np.array([5,10,15,20])
vector == 10 # '=='對array中的每一個元素進行判斷,返回布爾類型結果
v2 = (x2 == '4')
print(x2[v2]) #布爾類型array作爲索引


4.改變array 元素類型

print(x3.dtype)
x3_1 = x3.astype('str')
print(x3_1.dtype)#x3 int32, x3_1 <U11.


5.求最大值,最小值,求和

x3.min()#min value
x3.max()#max value
x3.sum(axis = 1) #行求和, axis = 0 列求和


6.常用函數

np.zeros((3,4))#得到3行4列零矩陣,1矩陣爲np.ones()


array([[0., 0., 0., 0.],
       [0., 0., 0., 0.],
       [0., 0., 0., 0.]])
 

np.arange(10,30,5) #生成一個序列,到30之前爲止。


array([10, 15, 20, 25])

np.arange(12).reshape(4,3) #reshape


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

np.random.random((2,3)) #generate random value
from numpy import pi
np.linspace(0,0.2*pi,10) #取均值爲0.2*pi


7.矩陣運算

a = np.array([20,30,40,50])
b = np.arange(4)
c = a -b
print(a,b,c) #   + - * / **皆可
A = np.array([
            [1,1],
            [0,1]
])
B = np.array([
            [2,0],
            [3,4]
])
print(A*B) #點乘
print(A.dot(B)) #叉乘

 

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