numpy对象的常用属性
第一种方法装好python,然后打开终端输入pip install jupyter(如果觉得速度慢可以加上镜像站 -i https://pypi.douban.com/simple/),然后再输入pip install notebook (这里和前面一样,觉得慢就加镜像), 打开在终端输入 jupyter notebook。
另一种方法就是去anaconda官网下载anaconda。
如果用的第一种方法就需要 pip install numpy
import numpy as np # 导入这个库
data = np.arange(12).reshape(3,4) # 创建一个3行4列的数组
print(data) # 打印data
type(data) #展示data的类型,输出结果为 numpy.ndarray 表示为数组类型
求数组的维度的个数
data.ndim
求数组的维度
data.shape
求数组的元素类型
data.dtype
求数组的元素个数
data.size
求数组每个元素的字节大小
data.itemsize
特殊数组
np.zeros(): 全为0的数组
# 创建一个三行三列的0数组
np.zeros((3,3))
np.ones():全为1的数组
# 创建一个四行四列的全为1的数组
np.ones((4,4))
np.empty():创建一个空数组,里面的值是随机值,只分配了内存空间
# 创建一个5行5列的空数组
np.empty((5,5))
数组的类型转换 .astype()
import numpy as np
data_1 = np.array([[1,2,3],[4,5,6]])
print(data_1)
# 查询数组类型
data_1.dtype
对数组进行数据类型转换
常见的有:int8,16,32,64,float8,16,32,64,uint8,16,32,64
data_1.astype(np.float64)
数组广播
两个或两个以上数组广播需要满足的条件(满足其中之一即可):
-
数组的某一维度等长
-
其中一个数组的某一维度为1
下面为第二种情况
data_2 = np.array([[1],[2],[3],[4]])
data_3 = np.array([1,2,3])
data_2+data_3
输出结果为:
array([[2, 3, 4],
[3, 4, 5],
[4, 5, 6],
[5, 6, 7]])
下面为第一种情况
data_2 = np.array([[1,2,3],[2,3,4],[3,4,5],[4,5,6]])
data_3 = np.array([1,2,3])
data_2+data_3
输出结果为:
array([[2, 4, 6],
[3, 5, 7],
[4, 6, 8],
[5, 7, 9]])
当有三个数组时的第一种情况:
data_2 = np.array([[1,2,3],[2,3,4],[3,4,5],[4,5,6]])
data_3 = np.array([1,2,3])
data_4 = np.array([4,5,6])
输出结果:
array([[ 6, 9, 12],
[ 7, 10, 13],
[ 8, 11, 14],
[ 9, 12, 15]])
当有三个数组时的第二种情况:
data_2 = np.array([[1],[2],[3],[4]])
data_3 = np.array([1,2,3])
data_4 = np.array([4,5,6])
输出结果为:
array([[ 6, 8, 10],
[ 7, 9, 11],
[ 8, 10, 12],
[ 9, 11, 13]])