美文网首页Numpy学习笔记
使用Numpy创建array

使用Numpy创建array

作者: 李小夭 | 来源:发表于2019-07-17 16:55 被阅读1次

创建array的基本形式:a = np.array()
括号中需要输入list形式,输出的结果与列表形式类似,但是无逗号分隔。
以下为例子:

import numpy as np
a = np.array([2,23,4])
print(a)

[ 2 23  4]
※ 在numpy中用dtype来定义type数据类型
  1. 定义整数int(也可以定义成int64或int32)
    位数越少,占用空间越少。位数越多,精度越高。
a = np.array([2,23,4],dtype = np.int)
print(a.dtype)

int64
  1. 定义成小数float
a = np.array([2,23,4],dtype = np.float)
print(a.dtype)

float64
※ 定义二维数组,记得在外面再套个列表
a = np.array([[2,23,4],[2,23,4]])
print(a)

[[ 2 23  4]
 [ 2 23  4]]
※ 创建全部为0的矩阵

需要定义size,在括号中输入几行几列

a = np.zeros((3,4),dtype = int)
print(a)

[[0 0 0 0]
 [0 0 0 0]
 [0 0 0 0]]
※ 创建全部为1的矩阵
a = np.ones((3,4),dtype = int)
print(a)

[[1 1 1 1]
 [1 1 1 1]
 [1 1 1 1]]
※ 生成有序的数列,与python中range类似
  1. 输入起始值,终止值和步长。
    例如创建一个10-19,步长为2的数组
a = np.arange(10,20,2)
print(a)

[10 12 14 16 18]
  1. 创建0-11共12位,3行4列的数组
a = np.arange(12).reshape((3,4))
print(a)

[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
  1. 生成线段
    输入起始值,终止值以及分成多少段,将自动匹配步长。
a = np.linspace(1,10,5)
print(a)

[ 1.    3.25  5.5   7.75 10.  ]


a = np.linspace(1,10,6).reshape((2,3)) #更改形状
print(a)

[[ 1.   2.8  4.6]
 [ 6.4  8.2 10. ]]

Numpy学习教程来源请戳这里

相关文章

网友评论

    本文标题:使用Numpy创建array

    本文链接:https://www.haomeiwen.com/subject/fmkclctx.html