numpy自学笔记__数组

参考资料:

创建数组

import numpy as np

# 方法一
t1 = np.array([1, 2, 3, 4])
print(t1)
print(type(t1))
# [1 2 3 4]
# <class 'numpy.ndarray'>

#方法二
t2 = np.array(range(1, 4)]
print(t2)
# [1 2 3]

#方法三
t3 = np.arange(0, 4)
print(t3)
print(t3.dtype)			# dtype是数组中存储的数据类型
# [1 2 3 4]
# int32

修改数组的数据类型

# 指定数组中的数据类型
t1 = np.arange(0, 4, 1, 'float32')
print(t1)
print(t1.dtype)
# [0. 1. 2. 3.]
# float32

#修改数组中的数据类型
t2 = t1.astype('bool')		# 不会改变t1中的数据类型
print(t2)
print(t2.dtype)
# [False  True  True  True]
# bool

# 固定数组中小数的位数
t3 = np.array([random.random() for i in range(5)])
print(t3)
t4 = np.round(t3, 2)			# 四舍五入
print(t4)
# [0.0271696  0.64183147 0.77604475 0.62665816 0.46107218]
# [0.03 0.64 0.78 0.63 0.46]

数组的形状

t1 = np.array([[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]])
print(t1.shape)						# 查看数组的形状
t2 = t1.reshape((3, 2, 2))			#修改数组的形状
print(t2.shape)
t3 = t2.flatten()       			# 将数组展开成一维
print(t3)
# (4, 3)
# (3, 2, 2)
# [1 2 3 2 3 4 3 4 5 4 5 6]

数组的计算

# 数组和数字进行计算
t1 = np.arange(-2, 4)
print(t1)
print(t1+5)
print(t1/0)
# [-2 -1  0  1  2  3]
# [3 4 5 6 7 8]
# [-inf -inf  nan  inf  inf  inf]		# 0/0无意义, 负数/0得负无穷, 正数/0得正无穷

# 数组和数组进行计算
## 数组大小相同
t1 = np.arange(0, 24).reshape(4, 6)
t2 = np.arange(24,48).reshape(4, 6)
print(t1*t2)        # 则对应位置的数据进行计算
# [[   0   25   52   81  112  145]
#  [ 180  217  256  297  340  385]
#  [ 432  481  532  585  640  697]
#  [ 756  817  880  945 1012 1081]]

广播原则: 如果两个数组的后缘维度(trailing dimension,即从末尾开始算起的维度)的轴长度相符,或其中的一方的长度为1,则认为它们是广播兼容的。广播会在缺失和(或)长度为1的维度上进行。

轴在numpy中用0, 1, 2, 3…表示. 对于一维数组, 只有一个0轴, 对于三维数组, 有0, 1, 2三个轴

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值