NumPy 创建数组

NumPy 创建数组

ndarray 数组除了可以使用底层 ndarray 构造器来创建外,也可以通过以下几种方式来创建。

numpy.empty

numpy.empty 方法用来创建一个指定形状(shape)、数据类型(dtype)且未初始化的数组:
numpy.empty(shape, dtype = float, order = 'C')
参数说明:
在这里插入图片描述

#创建三行两列的数组
import numpy as np 
x = np.empty([3,2], dtype = int) 
print (x)

# 注意 − 数组元素为随机值,因为它们未初始化。
#[[ 6917529027641081856  5764616291768666155]
# [ 6917529027641081859 -5764598754299804209]
# [          4497473538      844429428932120]]

numpy.zeros

创建指定大小的数组,数组元素以 0 来填充:
numpy.zeros(shape, dtype = float, order = 'C')
参数说明:
在这里插入图片描述

import numpy as np
 
# 默认为浮点数
x = np.zeros(5) 
print(x)
# [0. 0. 0. 0. 0.]
 
# 设置类型为整数
y = np.zeros((5,), dtype = np.int) 
print(y)
# [0 0 0 0 0]

# 自定义类型
z = np.zeros((2,2), dtype = [('x', 'i4'), ('y', 'i4')])  
print(z)
#[[(0, 0) (0, 0)]
# [(0, 0) (0, 0)]]

numpy.ones

创建指定形状的数组,数组元素以 1 来填充:
numpy.ones(shape, dtype = None, order = 'C')
参数说明:
在这里插入图片描述

import numpy as np
 
# 默认为浮点数
x = np.ones(5) 
print(x)
 # [1. 1. 1. 1. 1.]
# 自定义类型
x = np.ones([2,2], dtype = int)
print(x)
#[[1 1]
# [1 1]]

NumPy 从已有的数组创建数组

numpy.asarray

numpy.asarray 类似 numpy.array,但 numpy.asarray 参数只有三个,比 numpy.array 少两个。

numpy.asarray(a, dtype = None, order = None)

参数说明:
在这里插入图片描述

#将列表转换为 ndarray:
import numpy as np 
 
x =  [1,2,3] 
a = np.asarray(x)  
print (a)
#[1  2  3]


# 将元组转换为 ndarray:
import numpy as np 
 
x =  (1,2,3) 
a = np.asarray(x)  
print (a)
# [1  2  3]


# 将元组列表转换为 ndarray:
import numpy as np 
 
x =  [(1,2,3),(4,5)] 
a = np.asarray(x)  
print (a)
# [(1, 2, 3) (4, 5)]

设置了 dtype 参数:

import numpy as np 
 
x =  [1,2,3] 
a = np.asarray(x, dtype =  float)  
print (a)
# [ 1.  2.  3.]

numpy.frombuffer

numpy.frombuffer 用于实现动态数组。

numpy.frombuffer 接受 buffer 输入参数,以流的形式读入转化成 ndarray 对象。

numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0)

参数说明:
在这里插入图片描述

import numpy as np 
 
s =  b'Hello World' 
a = np.frombuffer(s, dtype =  'S1')  
print (a)
# [b'H' b'e' b'l' b'l' b'o' b' ' b'W' b'o' b'r' b'l' b'd']

numpy.fromiter

numpy.fromiter 方法从可迭代对象中建立 ndarray 对象,返回一维数组。

numpy.fromiter(iterable, dtype, count=-1)

在这里插入图片描述

import numpy as np 
 
# 使用 range 函数创建列表对象  
list=range(5)
it=iter(list)
 
# 使用迭代器创建 ndarray 
x=np.fromiter(it, dtype=float)
print(x)
# [0. 1. 2. 3. 4.]

numpy中array的行数和列数

import numpy as np
x = np.array([[1,2,5],[2,3,5],[3,4,5],[2,3,6]])
# 输出数组的行和列数
print(x.shape) # (4, 3)
# 只输出行数
print(x.shape[0]) # 4
# 只输出列数
print (x.shape[1]) # 3

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值