云计算百科
云计算领域专业知识百科平台

小杰python高级(three day)——numpy库

1.numpy数组的操作

(1)数组的连接

stack

        该函数可以实现多个数组的堆叠(连接),会创建新的轴,用于沿着新的轴连接一系列数组,所有数组必须具有相同的形状

numpy.stack(arrays, axis=0, out=None)

参数:arrays:数组元素或列表

(2)数组的分割

split

        该函数用于沿着指定的轴将数组分割成多个子数组,可以指定要分割的数组、分割的位置或子数组的数量。

numpy.split(ary, indices_or_sections, axis=0)

参数:ary:数组

        indices_or_sections:可以是一个整数,表示要将数组平均分割成多少个子数组;也可以是一个整数列表,表示分割的位置。

import numpy as np

# a = np.array([1,2,3,4,5])
# b = np.array([6,7,8,9,0])
# # 将多个数组进行堆叠,维度会发生变化
# c = np.stack([a, b], axis=1)
# print(c)

arr = np.ones([3,6])
# 数组的分割,可以指定整数或下标的列表
b, c, d = np.split(arr, [1,2], axis=1)
print(b)
print(c)
print(d)

(3)where函数

        numpy.where是 NumPy 库中的一个函数,它可以根据指定的条件返回满足该条件的元素的索引。

        当 numpy.where 接受一个条件作为参数时,它会返回一个元组,每个元素是一个numpy数组,其中包含满足该条件的元素的索引(行索引、列索引)。

numpy.where(condition)

参数:一个布尔数组或条件表达式

返回值:一个元组,其中包含满足条件的元素的索引

import numpy as np
arr = np.array([4,6,6,3,5,2,9])
cond = arr>4
# 返回bool数组
print(cond)
ret = np.where(cond)
# 返回为真的下标
print(ret)
# 通过下标返回值
print(arr[ret])

赞(0)
未经允许不得转载:网硕互联帮助中心 » 小杰python高级(three day)——numpy库
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!