1.1數組對象基礎javascript
import numpy as np
np.__version__
data = np.array([1,2,3,4,5])
data
type(data)
dir(data)
data?
# 數組元素的類型
data.dtype
# 修改數組類型
new_data = data.astype(np.float)
new_data
new_data.dtype
data,data.dtype
# 數組的外貌
a = np.array([1,2,3])
b = np.array([1.0,2.0,3.0])
a.dtype,b.dtype
a.shape
b.shape
c = np.array([1.0,2.0,3.0,4.0])
c.shape
# 維度
a.ndim
# 返回元素個數
a.size
c.size
np.array?
a = np.array([1,2,3,4])
b = np.array([1,2,3,4],dtype=float)
a
a.dtype
a.shape
a.size
a.ndim
b
b.dtype
# 多維數組,數組的元素類型必須一致
da = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
da
np.array([[1,2,3],[4,5,6,7],[8,9]])
da.shape
da.size
db = np.array([[1,2,3,4,5,6,7]],ndmin=2)
db
db.shape
db.ndim
dc = np.array([1,2,3,4,5,6,7])
dc
dc.shape
dc.ndim
a
de = np.array(a,dtype=complex)
de
de.dtype
# 用函數建立數組
np.zeros((2,10))
np.zeros?
# zeros(shape, dtype=float, order='C')
同一種元素的數組css
np.ones((6,))
# 一維數組才能這樣寫
np.ones(6)
da
da.shape
np.ones(da.shape)
np.ones_like(da)
np.ones_like(da,dtype=np.float)
df = 6.4 * np.ones_like(da)
df
對角線獨特的數組html
np.eye(4,dtype=int)
np.eye(4,dtype=int,k=1)
np.eye(4,dtype=int,k=-1)
np.identity(4)
np.diag([1,2,3,4])
np.diag([1,2,3,4],k=1)
de = np.arange(16).reshape((4,4))
de
np.diag(de)
np.diag(de,k=-1)
元素是等差和等比的數組html5
# arange([start,] stop[, step,], dtype=None)
np.arange(1,100,3)
np.arange?
# np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
np.linspace(1,10,4)
np.linspace?
np.logspace?
# np.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)
np.logspace(2,3,num=4)
import math
math.log10(215.443469)
math.log10(464.15888336)
建立自定義類型的數組java
my_type = np.dtype({"names":['book','version'],"formats":['S40',np.int]})
my_type
my_books = np.array([("python",2),("java",1)],dtype=my_type)
my_books
# 同my_type
my_type2 = np.dtype([('book','S40'),('version','<i8')])
my_books['book']
my_books['book'][0]
my_books[0]
my_books[0]['book']
# 修改記錄
my_books[0]['book'] = "learn python"
my_books
用from系列函數建立數組python
#s = 'hello world'
np.frombuffer(b'hello world',dtype='S1',count=5,offset=6)
np.frombuffer?
def foo(x):
return x + 1
np.fromfunction(foo,(5,),dtype=np.int)
np.fromfunction(lambda i,j:(i+1)*(j+1),(9,9),dtype=np.int)