numpy get started
-
导入numpy库,并查numpy版本
In [1]: import numpy as np In [2]: np.__version__ '1.14.0'
一、创建ndarray
-
1.使用np.array()由python list 创建
In [1]: list1 = [1,2,3,4,5] nparray1 = np.array(list1) In [2]: nparray1 Out [2]: array([1, 2, 3, 4, 5]) In [3]: list1 Out [2]: [1,2,3,4,5] In [1]:list3 = [1,2,3,4,5] # numpy提供了各种数据类型的表达方式 arr3 = np.array(object=list3, dtype=np.float32) arr3 Out [1]:array([1, 2, 3, 4, 5]) In[1]:# 构建一个高维数组 list4 = [[1,2,3],[4,5,6]] arr4 = np.array(list4) arr4 Out[2]:array([[1, 2, 3], [4, 5, 6]]) 注意: numpy默认ndarray的所有元素的类型是相同的 如果传进来的列表中包含不同的类型,则统一为同一类型,优先级:str>float>int
-
2.使用np的routines函数创建
-
- np.ones(shape, dtype=None, order=‘C’)
In[1]:np.ones(shape=10)
Out[1]:array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
In[1]:np.ones(shape=(2,3))
Out[1]:array([[1., 1., 1.],
[1., 1., 1.]])
In[1]:np.ones(shape=(2,3), dtype=np.int8)
Out[1]:array([[1, 1, 1],
[1, 1, 1]], dtype=int8)
- np.ones(shape, dtype=None, order=‘C’)
-
- np.zeros(shape, dtype=float, order=‘C’)
In[1]:np.zeros(shape=(3,3), dtype=np.int8)
Out[1]:array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]], dtype=int8)
- np.zeros(shape, dtype=float, order=‘C’)
-
- np.full(shape, fill_value, dtype=None, order=‘C’)
In[1]:np.full(shape=(3,3), fill_value=5, dtype=np.int8)
Out[1]:array([[5, 5, 5],
[5, 5, 5],
[5, 5, 5]], dtype=int8)
- np.full(shape, fill_value, dtype=None, order=‘C’)
-
- np.eye(N, M=None, k=0, dtype=float) 对角线为1其他的位置为0
In[1]:np.eye(N=3,M=5,k=-1)
Out[1]:array([[0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0.],
[0., 1., 0., 0., 0.]])
- np.eye(N, M=None, k=0, dtype=float) 对角线为1其他的位置为0
-
- np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
In[1]:# 生成一维的等差数列
np.linspace(0,10,num=10,endpoint=False)
Out[1]:array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])
- np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
-
- np.arange([start, ]stop, [step, ]dtype=None)
In[1]:np.arange(0,10,1)
Out[1]:array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
- np.arange([start, ]stop, [step, ]dtype=None)
-
- np.random.randint(low, high=None, size
-