In [1]:
import numpy as np
In [11]:
# 创建数组
a = np.array([1,2,3,4,5])
In [12]:
a
Out[12]:
In [9]:
np.array(range(1,6))
Out[9]:
In [10]:
np.arange(1,6)
Out[10]:
In [13]:
# 数组的类名
type(a)
Out[13]:
In [14]:
# 数据的类型
a.dtype
Out[14]:
In [15]:
t1 = np.arange(12)
In [16]:
t1
Out[16]:
In [17]:
t1.shape
Out[17]:
In [18]:
t2 = np.array([[1,2,3], [2,3,4]])
In [19]:
t2
Out[19]:
In [20]:
# 数据的形状
t2.shape
Out[20]:
In [21]:
t3 = np.array([[[1,2,3], [4,5,6]], [[7,8,9], [10,11,12]]])
In [22]:
t3.shape
Out[22]:
In [23]:
t3
Out[23]:
In [24]:
t4 = np.arange(12)
In [25]:
# 3行4列
t4.reshape((3, 4))
Out[25]:
In [26]:
t4.reshape((3, 5))
In [8]:
t5 = np.arange(24)
In [9]:
# 2块2行6列
t5.reshape(2, 2, 6)
Out[9]:
In [10]:
# 2块3行4列
t5.reshape(2, 3, 4)
Out[10]:
In [11]:
t5
Out[11]:
可以看出,reshape方法,没有改变t5的原始值,说明方法本身就存在return方法¶
In [31]:
# 需要改变的话
t5 = t5.reshape((4, 6))
如果t5为None的话,就说明某方法会直接改变原始值,不存在return方法¶
In [32]:
t5
Out[32]:
In [2]:
a = np.array([1,0,1,0],dtype=np.bool) # 或者使用dtype='?'
In [3]:
a
Out[3]:
In [4]:
# 修改数组的数据类型
a.astype('i1') # 或者使用a.astype(np.int8)
Out[4]:
In [5]:
# 修改浮点型的小数位数
b = np.array([0.03214, 0.4243564, 0.42566453, 0.4134234, 0.1235, 0.85763])
In [6]:
np.round(b, 2)
Out[6]:
In [12]:
t5
Out[12]:
In [13]:
t5 = t5.reshape((4, 6))
In [14]:
t5
Out[14]:
In [15]:
# 将数组转换成一维数组
t5.flatten()
Out[15]:
数组和数的计算¶
In [22]:
a = np.arange(24).reshape(2,2,6)
In [23]:
a
Out[23]:
In [24]:
# 加法
a + 1
Out[24]:
In [25]:
# 乘法
a * 3
Out[25]:
数组与数组的计算¶
In [26]:
a = np.arange(12).reshape(2, 6)
In [28]:
b = np.arange(21, 33).reshape(2, 6)
In [29]:
a
Out[29]:
In [30]:
b
Out[30]:
数组和数组加减法¶
In [31]:
a + b
Out[31]:
In [32]:
a - b
Out[32]:
数组和数组的乘除法¶
In [33]:
a * b
Out[33]:
In [34]:
a / b
Out[34]:
In [35]:
np.round(a / b, 2)
Out[35]:
不同维度的数组计算¶
In [36]:
# 2行6列
a
Out[36]:
In [37]:
b = np.array([[1,2,3], [2,3,4]])
In [38]:
# 2行3列
b
Out[38]:
维度完全没有关系¶
In [39]:
a + b
In [40]:
a * c
In [41]:
# 2行6列
a
Out[41]:
In [42]:
# 1行6列
b = np.array([2,3,4,5,6,7])
In [43]:
a.shape
Out[43]:
In [44]:
b.shape
Out[44]:
如果有(从右向左)维度相同的话,操作是可以执行的,按照对应维度广播操作¶
In [45]:
# 2行6列
a
Out[45]:
In [48]:
# 1行6列
b
Out[48]:
In [49]:
# 一整行一整行的计算
a + b
Out[49]:
In [50]:
# 一整行一整行的计算
a * b
Out[50]:
In [52]:
c = np.array([[1],[2]])
In [53]:
c
Out[53]:
In [55]:
c.shape
Out[55]:
In [57]:
a.shape
Out[57]:
In [59]:
# 2行6列
a
Out[59]:
In [60]:
# 2行1列
c
Out[60]:
In [61]:
# 一列一列的计算
a + c
Out[61]:
In [62]:
# 一列一列的计算
a / c
Out[62]:
In [75]:
a = np.arange(27).reshape(3,3,3)
In [76]:
b = np.arange(18).reshape(3,3,2)
In [77]:
c = np.arange(6).reshape(3,2)
In [78]:
a.shape
Out[78]:
In [79]:
b.shape
Out[79]:
In [80]:
c.shape
Out[80]:
In [81]:
a + c
In [82]:
b + c
Out[82]:
In [ ]: