Python 玩转数据 2 - NumPy ndarray 数组的创建

引言

主要介绍 NumPy 多维数组的创建,更多 Python 进阶系列文章,请参考 Python 进阶学习 玩转数据系列

内容提要:

  1. np.empty(): 创建空的未初始化数组
  2. 数组存储顺序
  3. np.zeros(), np.ones(), np.full(), np.eye(), np.arange(),np.linspace(): 按默认给定的值(0,1,给定的其它值)创建数组, 或则矩阵对角线为1,或则从一个线性序列范围中填充数组
  4. np.array(python_obj): 从一个 python object 中创建
  5. 强制向上类型转换 Coercion Upcasting
  6. np.random.random(), np.random.normal(), np.random.randint(): 创建随机数数组,从正态分布或均匀分布中随机浮点数或整数

创建 Empty Array 空数组

numpy.empty 方法用来创建一个指定形状(shape)、数据类型(dtype)且未初始化的数组

empty(shape, dtype=float, order=‘C’)

参数描述
shape数组形状
dtype数据类型,可选
order有"C"和"F"两个选项,分别代表,行优先和列优先,在计算机内存中的存储元素的顺序。

举例:

import numpy as np

array_default = np.empty (shape = (2,3))
array_default_int = np.empty (shape = (2,3), dtype=int)
array_float_16 = np.empty (shape = (2,3), dtype = np.float16, order = 'F')
array_float = np.empty (shape = (2,3), dtype = float, order = 'F')

print("array_default:{}\n".format(array_default))
print("array_default_int:{}\n".format(array_default_int))
print("array_float_16:{}\n".format(array_float_16))
print("array_float:{}\n".format(array_float))

输出:

注意, 数组元素为随机值,因为它们未初始化,所以每次运行的值都会不一样,也就是说需要用户手动设置其值。

array_default:[[9.34609111e-307 3.56043054e-307 1.11261027e-306]
 [2.33646845e-307 3.44898841e-307 3.22646744e-307]]

array_default_int:[[ 924184752      32765  924189296]
 [     32765  537536802 1042292768]]

array_float_16:[[0.000e+00 1.132e-06 3.731e-05]
 [1.229e+04 0.000e+00 0.000e+00]]

array_float:[[1.24610723e-306 1.29060871e-306 9.34604358e-307]
 [1.37962320e-306 1.11258446e-306 1.44635488e-307]]

数组存储顺序

一个多维数组在内存中的存储是按一维线性连续存储的:
● Fortran-style (column-wise): 缓存被优化按访问优先,按的顺序连续存储数据
● C-style (row-major): 缓存被优化按访问优先,按的顺序连续存储数据

性能影响
选择不同的存储方式会影响数组中个元素的量化计算性能。

例如:计算一个数组每行的元素总合
那么按存储的性能肯定要优于按存储的性能

例如:计算一个数组每列的元素总合
那么按存储的性能肯定要优于按存储的性能
在这里插入图片描述

创建数组:填充预先给定的值

方法说明
numpy.zeros(shape, dtype = float, order = ‘C’)填充 0
numpy.ones(shape, dtype = None, order = ‘C’)填充 1
np.full ((2,5), fill_value = 3.14)填充 fill_value 的值
np.eye(N, M=None, k=0, dtype=<class ‘float’>, order=‘C’)N-> 行数; M->列数; k->对角线或斜线的 index;
np.arange(start, stop, step, dtype)使用 arange 函数创建数值范围; start:起始值,默认为0; stop:终止值(不包含);step: 步长,默认为1;dtype:返回ndarray的数据类型,如果没有提供,则会使用输入数据的类型。
np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)创建一个一维数组,数组是一个等差数列. start:序列的起始值; stop:序列的终止值; num:要生成的等步长的样本数量,默认为50;endpoint:该值为 true 时,数列中包含stop值,反之不包含,默认是True;retstep:如果为 True 时,生成的数组中会显示间距,反之不显示;dtype:ndarray 的数据类型

举例:

import numpy as np

aray_zeros = np.zeros(shape = (2,5), dtype = int, order = 'F')
array_ones = np.ones(shape = (2,5), dtype = float, order = 'C')
array_full = np.full(shape = (3, 5), fill_value=3.14, dtype = float, order = 'F')
array_eye_1 = np.eye(3)
array_eye_2 = np.eye(N=4, M=5, k=1, dtype=int, order='C')
array_arange_1 = np.arange(5)
array_arange_2 = np.arange(1, 10, 2)
array_lines_1 = np.linspace(2.0, 3.0, num=5)
array_lines_2 = np.linspace(2.0, 3.0, num=5, retstep=True)

print("aray_zeros:{}\n".format(aray_zeros))
print("array_ones:{}\n".format(array_ones))
print("array_full:{}\n".format(array_full))
print("array_eye_1:{}\n".format(array_eye_1))
print("array_eye_2:{}\n".format(array_eye_2))
print("array_arange_1:{}\n".format(array_arange_1))
print("array_arange_2:{}\n".format(array_arange_2))
print("array_lines_1:{}\n".format(array_lines_1))
print("array_lines_2:{}\n".format(array_lines_2))

输出

aray_zeros:[[0 0 0 0 0]
 [0 0 0 0 0]]

array_ones:[[1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1.]]

array_full:[[3.14 3.14 3.14 3.14 3.14]
 [3.14 3.14 3.14 3.14 3.14]
 [3.14 3.14 3.14 3.14 3.14]]

array_eye_1:[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]

array_eye_2:[[0 1 0 0 0]
 [0 0 1 0 0]
 [0 0 0 1 0]
 [0 0 0 0 1]]

array_arange_1:[0 1 2 3 4]

array_arange_2:[1 3 5 7 9]

array_lines_1:[2.   2.25 2.5  2.75 3.  ]

array_lines_2:(array([2.  , 2.25, 2.5 , 2.75, 3.  ]), 0.25)

从 python object 中创建数组

NumPy数组描述
np.array(list_obj)从 list 列表中创建
np.array(tuple_obj)从 tuple 元组中创建
np.array(set_obj)从 set 集合中创建
np.array(dict_obj)从 dict 字典中创建

举例:

import numpy as np

array_from_list_1 = np.array ( ['NumPy', 'supports', 'vectorized', 'operations'])
array_from_list_2 = np.array ([[1, 2, 3], [4, 5, 6]])
array_from_list_3 = np.array ( [range(i, i+3) for i in [2, 4, 6]])

array_from_tuple = np.array((1, 2, 3))
array_from_set = np.array({1, 2, 2, 3})
array_from_dict = np.array({ 'language' : 'Python', "Hobby":"Reading"})

print("array_from_list_1:{}\n".format(array_from_list_1))
print("array_from_list_2:{}\n".format(array_from_list_2))
print("array_from_list_3:{}\n".format(array_from_list_3))
print("array_from_tuple:{}\n".format(array_from_tuple))

print("array_from_set:{}\n".format(array_from_set))
print("array_from_set attribute: shape:{}; ndim:{}; size:{}\n".format(array_from_set.shape, array_from_set.ndim, array_from_set.size))
print("array_from_dict:{}\n".format(array_from_dict))
print("array_from_dict attribute: shape:{}; ndim:{}; size:{}\n".format(array_from_dict.shape, array_from_dict.ndim, array_from_dict.size))

输出:
注意:从 set,dict 中创建 numpy 数组,是 0 维数组,size 是 1

array_from_list_1:['NumPy' 'supports' 'vectorized' 'operations']

array_from_list_2:[[1 2 3]
 [4 5 6]]

array_from_list_3:[[2 3 4]
 [4 5 6]
 [6 7 8]]

array_from_tuple:[1 2 3]

array_from_set:{1, 2, 3}

array_from_set attribute: shape:(); ndim:0; size:1

array_from_dict:{'language': 'Python', 'Hobby': 'Reading'}

array_from_dict attribute: shape:(); ndim:0; size:1

强制向上类型转换 Coercion Upcastin

我们知道 NumPy 中的数组元素类型必须是一一致的,当数组中的元素类型不一致时,NumPy 会尽可能强制向上类型转化,除非明确数据类型。

例如:
np.array ( [3.14, 2, 3] ) -> 强制转换成浮点类型 array ( [ 3.14, 2.0, 3.0 ] )
np.array ( [2, 3.14, 3] ) -> 尽管第 1 个元素是整型,强制转换成浮点类型 array ( [ 2.0, 3.14, 3.0 ] )
np.array ([‘1’, 2, 3]) -> 强制转换成字符型 array([‘1’, ‘2’, ‘3’], dtype=’<U1’)
np.array ([‘1’, 2, 3], dtype = ‘int8’) -> 按明确给定的数据类型转换 array([1, 2, 3], dtype=int8)

创建随机数数组

随机数组描述
np.random.random (size = (3,5))Uniform Distribution of Floats from [0.0, 1.0) -> 从[0.0, 1.0)均匀分布的随机数
np.random.normal (loc = 2, scale = 1, size = (3,5))Normal Distribution动态分布的随机数, loc: mean; scale: standard deviation (spread or “width”)
np.random.randint (low = 0, high = 10, size = (2, 3))Random Integers from an Interval -> 区间随机整数
举例:
array_random_random = np.random.random(size=(3,5))
array_random_normal = np.random.normal(loc = 2, scale = 1, size = (3,5))
array_random_int = np.random.randint(low = 0, high = 10, size = (2, 3))

print("array_random_random:{}\n".format(array_random_random))
print("array_random_normal:{}\n".format(array_random_normal))
print("array_random_int:{}\n".format(array_random_int))

输出:

array_random_random:[[0.02164541 0.72035649 0.69718817 0.91684897 0.36921595]
 [0.32850542 0.47149381 0.04184023 0.39958435 0.62943443]
 [0.62590949 0.42814604 0.11767369 0.71687164 0.51742262]]

array_random_normal:[[1.886419   2.32612002 2.31179881 1.24693448 1.37626366]
 [1.54387266 2.0334366  3.68800144 1.45346514 3.36354338]
 [3.08620338 1.0974769  3.18664    3.64974797 2.27638157]]

array_random_int:[[9 7 0]
 [7 7 7]]
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值