【numpy笔记_3】常用的创建数组操作
2024-04-09 17:00:58  阅读数 165

创建一个array对象,一般分为两种情况:

1、有原始数据;

一般将原始数据转化为列表或迭代器直接转为array对象,再进行维度变形(reshape()方法)。
—— np.array() 方法,接收原始数据,指定dtype数据类型;
—— obj.reshape() 方法,接收一个size元组。

import numpy as np
datas = [1,2,3,4,5,6,7,8,9,10,11,12]
arr_data = np.array(datas, dtype=np.int32)
arr_data_1 = arr_data.reshape((4, 3))  # 4行 3列
arr_data_2 = arr_data.reshape((2, 2, 3))  # 2个 2行 3列
# reshape()方法对1darray进行重新塑形,参数是一个元组。reshape的结构与元素总数要一致,不再赘述
print(arr_data)
print('*'*20)
print(arr_data_1)
print('*'*20)
print(arr_data_2)
print('*'*20)
# 运行结果:
[ 1  2  3  4  5  6  7  8  9 10 11 12]
********************
[[ 1  2  3]
 [ 4  5  6]
 [ 7  8  9]
 [10 11 12]]
********************
[[[ 1  2  3]
  [ 4  5  6]]

 [[ 7  8  9]
  [10 11 12]]]
********************

将迭代器转为array对象使用np.fromiter()方法,用法基本相同:

datas = [1,2,3,4,5,6,7,8,9,10,11,12]
iter_data = iter(datas)   # 列表变迭代器
arr_data = np.fromiter(iter_data, dtype=np.int32, count=6).reshape((2, 3))
#                      迭代器对象    数据类型      读取几个元素,默认-1即全部读取
print(arr_data)
# 运行结果:
[[1 2 3]
 [4 5 6]]

2、新建数据;
  • 指定区间的数组:numpy.arange()方法;用法与range()基本一致。
  • 指定区间的等差数组:np.linspace()方法;
  • 指定区间的等比数组:np.logspace()方法;
  • 创建随机数组:np.random()方法。
import numpy as np
arr_data_1 = np.arange(start=1, stop=13, step=1, dtype=np.int32)
# strat : 起
# stop: 止(开区间)
# step: 步长
# dtype: 数据类型
arr_data_2 = np.linspace(start=1, stop=13, num=6, endpoint=False, dtype=np.int32)
# strat : 起
# stop: 止
# num: 生成几个数
# endpoint: 是否包含终点。默认包含True
# dtype: 数据类型
arr_data_3 = np.logspace(start=3, stop=13, num=4, endpoint=True, base=2, dtype=np.int32)
# strat : 起始对数(起始值)
# stop: 终止对数(终止值)
# num: 生成几个数,默认50
# endpoint: 是否包含终点。默认包含True
# base: 底,默认10
# dtype: 数据类型
print(arr_data_1)
print('*'*20)
print(arr_data_2)
print('*'*20)
print(arr_data_3)
# 运行结果:
[ 1  2  3  4  5  6  7  8  9 10 11 12]
********************
[ 1  3  5  7  9 11]
********************
[   8   80  812 8192]

numpy底层封装了random模块的功能,用以实现一系列随机数的操作
使用方法和random方法并无二致,这里简单介绍下几个常用的随机方法,其他不再过多介绍:

import numpy as np
# 【范围内随机取整数】
arr1 = np.random.randint(1,10,5)  # 起点,终点(不包),取几个
print(f'随机生成的整数组arr1:{arr1}')

# 【数组内随机取一个数】
random_number = np.random.choice(arr1)
print(f'从arr1随机取一个数:{random_number}')

# 【打散数组的元素】
np.random.shuffle(arr1)   # 。shuffle()是一个功能,没有返回值
print(f'将arr1的元素顺序随机打散:{arr1}')

# 【随机取0~1之间的小数】
arr2 = np.random.random(5)   # 随机0~1取数,取几个
print(f'随机生成的0~1的五个数组arr2:{arr2}')
# 运行结果:
随机生成的整数组arr1:[1 6 3 8 4]
从arr1随机取一个数:6
将arr1的元素顺序随机打散:[6 4 8 1 3]
随机生成的0~1的五个数组arr2:[0.41969365 0.81450626 0.99858456 0.41678652 0.78860871]

以上是使用频率较高的数组创建操作,基本覆盖了多数场景;
其他很少用到的操作就不提了,有兴趣的同学再自行深入研究。