numpy计算
numpy位运算
位运算是一种在二进制数字的位级别上进行操作的一类运算,它们直接操作二进制数字的各个位,而不考虑数字的整体值。
位运算在计算机科学中广泛应用于优化和处理底层数据。
NumPy “bitwise_” 开头的函数是位运算函数。
NumPy 位运算包括以下几个函数:
| 函数 | 描述 | 操作符 |
|---|---|---|
| bitwise_and | 按位与,对数组元素执行位与操作 | & |
| bitwise_or | 按位或,对数组元素执行位或操作 | |
| bitwise_xor | 按位异或 | ^ |
| bitwise_not | 按位取反 | ~ |
| invert | 按位取反 | ~ |
| left_shift | 左移位运算,向左移动二进制表示的位 | << |
| right_shift | 右移位运算,向右移动二进制表示的位 | >> |
import numpy as np
arr1 = np.array([True, False, True], dtype=bool)arr2 = np.array([False, True, False], dtype=bool)
result_and = np.bitwise_and(arr1, arr2)result_or = np.bitwise_or(arr1, arr2)result_xor = np.bitwise_xor(arr1, arr2)result_not = np.bitwise_not(arr1)
print("AND:", result_and) # [False, False, False]print("OR:", result_or) # [True, True, True]print("XOR:", result_xor) # [True, True, True]print("NOT:", result_not) # [False, True, False]
# 按位取反arr_invert = np.invert(np.array([1, 2], dtype=np.int8))print("Invert:", arr_invert) # [-2, -3]
# 左移位运算arr_left_shift = np.left_shift(5, 2)print("Left Shift:", arr_left_shift) # 20
# 右移位运算arr_right_shift = np.right_shift(10, 1)print("Right Shift:", arr_right_shift) # 5字符串函数
以下函数用于对 dtype 为 numpy.string_或 numpy.unicode_ 的数组执行向量化字符串操作。 它们基于 Python 内置库中的标准字符串函数。
这些函数在字符数组类(numpy.char)中定义。
| 函数 | 描述 |
|---|---|
| add() | 对两个数组的逐个字符串元素进行连接 |
| multiply() | 返回按元素多重连接后的字符串 |
| center() | 居中字符串,并使用指定字符在左侧和右侧进行填充。 |
| capitalize() | 将字符串第一个字母转换为大写 |
| title() | 将字符串的每个单词的第一个字母转换为大写 |
| lower() | 数组元素转换为小写 |
| upper() | 数组元素转换为大写 |
| split() | 指定分隔符对字符串进行分割,并返回数组列表 |
| splitlines() | 返回元素中的行列表,以换行符分割 |
| strip() | 移除元素开头或者结尾处的特定字符 |
| join() | 通过指定分隔符来连接数组中的元素 |
| replace() | 使用新字符串替换字符串中的所有子字符串 |
| decode() | 数组元素依次调用str.decode |
| encode() | 数组元素依次调用str.encode |
- numpy.char.add()/multiply()/center()
numpy.char.add() 函数依次对两个数组的元素进行字符串连接。
import numpy as np
print ('连接两个字符串:')print (np.char.add(['hello'],[' xyz']))print ('\\n')
print ('连接示例:')print (np.char.add(['hello', 'hi'],[' abc', ' xyz']))
print (np.char.multiply('Runoob ',3))
# np.char.center(str , width,fillchar) :# str: 字符串,width: 长度,fillchar: 填充字符print (np.char.center('Runoob', 20,fillchar = '*'))- numpy.char.capitalize()/title()/lower()/upper()
import numpy as np
print (np.char.capitalize('runoob'))
print (np.char.capitalize('runoob'))
#操作数组print (np.char.lower(['RUNOOB','GOOGLE']))
# 操作字符串print (np.char.lower('RUNOOB'))- numpy.char.split()/splitlines()/strip()
numpy.char.split() 通过指定分隔符对字符串进行分割,并返回数组。默认情况下,分隔符为空格。
import numpy as np
# 分隔符默认为空格print (np.char.split ('i like runoob?'))# 分隔符为 .print (np.char.split ('www.runoob.com', sep = '.'))
# 换行符 \\n# \\n,\\r,\\r\\n 都可用作换行符。print (np.char.splitlines('i\\nlike runoob?'))print (np.char.splitlines('i\\rlike runoob?'))
# 移除字符串头尾的 a 字符print (np.char.strip('ashok arunooba','a'))
# 移除数组元素头尾的 a 字符print (np.char.strip(['arunooba','admin','java'],'a'))- numpy.char.join()/replace()/encode()/decode()
numpy.char.join() 函数通过指定分隔符来连接数组中的元素或字符串
import numpy as np
# 操作字符串print (np.char.join(':','runoob'))
# 指定多个分隔符操作数组元素print (np.char.join([':','-'],['runoob','google']))
print (np.char.replace ('i like runoob', 'oo', 'cc'))
a = np.char.encode('runoob', 'cp500')print (a)
print (np.char.decode(a,'cp500'))numpy数学函数
三角函数
NumPy 提供了标准的三角函数:sin()、cos()、tan()。
import numpy as np
a = np.array([0,30,45,60,90])print ('不同角度的正弦值:')# 通过乘 pi/180 转化为弧度print (np.sin(a*np.pi/180))print ('\\n')print ('数组中角度的余弦值:')print (np.cos(a*np.pi/180))print ('\\n')print ('数组中角度的正切值:')print (np.tan(a*np.pi/180))arcsin,arccos,和 arctan 函数返回给定角度的 sin,cos 和 tan 的反三角函数。
这些函数的结果可以通过 numpy.degrees() 函数将弧度转换为角度。
import numpy as np
a = np.array([0,30,45,60,90])print ('含有正弦值的数组:')sin = np.sin(a*np.pi/180)print (sin)print ('\\n')print ('计算角度的反正弦,返回值以弧度为单位:')inv = np.arcsin(sin)print (inv)print ('\\n')print ('通过转化为角度制来检查结果:')print (np.degrees(inv))print ('\\n')print ('arccos 和 arctan 函数行为类似:')cos = np.cos(a*np.pi/180)print (cos)print ('\\n')print ('反余弦:')inv = np.arccos(cos)print (inv)print ('\\n')print ('角度制单位:')print (np.degrees(inv))print ('\\n')print ('tan 函数:')tan = np.tan(a*np.pi/180)print (tan)print ('\\n')print ('反正切:')inv = np.arctan(tan)print (inv)print ('\\n')print ('角度制单位:')print (np.degrees(inv))舍入函数
-
numpy.around() 函数返回指定数字的四舍五入值。
# numpy.around(a,decimals)# a: 数组# decimals: 舍入的小数位数。 默认值为0。 如果为负,整数将四舍五入到小数点左侧的位置import numpy as npa = np.array([1.0,5.55, 123, 0.567, 25.532])print ('原数组:')print (a)print ('\\n')print ('舍入后:')print (np.around(a))print (np.around(a, decimals = 1))print (np.around(a, decimals = -1)) -
numpy.floor() 返回小于或者等于指定表达式的最大整数,即向下取整。
import numpy as npa = np.array([-1.7, 1.5, -0.2, 0.6, 10])print ('提供的数组:')print (a)print ('\\n')print ('修改后的数组:')print (np.floor(a)) -
numpy.ceil() 返回大于或者等于指定表达式的最小整数,即向上取整。
import numpy as npa = np.array([-1.7, 1.5, -0.2, 0.6, 10])print ('提供的数组:')print (a)print ('\\n')print ('修改后的数组:')print (np.ceil(a))
算术函数
NumPy 算术函数包含简单的加减乘除: add(),subtract(),multiply() 和 divide()。
需要注意的是数组必须具有相同的形状或符合数组广播规则。
import numpy as np
a = np.arange(9, dtype = np.float_).reshape(3,3)print ('第一个数组:')print (a)print ('\\n')print ('第二个数组:')b = np.array([10,10,10])print (b)print ('\\n')print ('两个数组相加:')print (np.add(a,b))print ('\\n')print ('两个数组相减:')print (np.subtract(a,b))print ('\\n')print ('两个数组相乘:')print (np.multiply(a,b))print ('\\n')print ('两个数组相除:')print (np.divide(a,b))-
numpy.reciprocal()
numpy.reciprocal() 函数返回参数逐元素的倒数。如 1/4 倒数为 4/1。
import numpy as npa = np.array([0.25, 1.33, 1, 100])print ('我们的数组是:')print (a)print ('\\n')print ('调用 reciprocal 函数:')print (np.reciprocal(a)) -
numpy.power()
numpy.power() 函数将第一个输入数组中的元素作为底数,计算它与第二个输入数组中相应元素的幂。
import numpy as npa = np.array([10,100,1000])print ('我们的数组是;')print (a)print ('\\n')print ('调用 power 函数:')print (np.power(a,2))print ('\\n')print ('第二个数组:')b = np.array([1,2,3])print (b)print ('\\n')print ('再次调用 power 函数:')print (np.power(a,b)) -
numpy.mod()
numpy.mod() 计算输入数组中相应元素的相除后的余数。 函数 numpy.remainder() 也产生相同的结果。
import numpy as npa = np.array([10,20,30])b = np.array([3,5,7])print ('第一个数组:')print (a)print ('\\n')print ('第二个数组:')print (b)print ('\\n')print ('调用 mod() 函数:')print (np.mod(a,b))print ('\\n')print ('调用 remainder() 函数:')print (np.remainder(a,b))
统计函数
-
numpy.amin() 和 numpy.amax()
numpy.amin() 用于计算数组中的元素沿指定轴的最小值。
numpy.amin(a, axis=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)# 参数说明:# a: 输入的数组,可以是一个NumPy数组或类似数组的对象。# axis: 可选参数,用于指定在哪个轴上计算最小值。如果不提供此参数,则返回整个数组的最小值。可以是一个整数表示轴的索引,也可以是一个元组表示多个轴。# out: 可选参数,用于指定结果的存储位置。# keepdims: 可选参数,如果为True,将保持结果数组的维度数目与输入数组相同。如果为False(默认值),则会去除计算后维度为1的轴。# initial: 可选参数,用于指定一个初始值,然后在数组的元素上计算最小值。# where: 可选参数,一个布尔数组,用于指定仅考虑满足条件的元素。numpy.amax() 用于计算数组中的元素沿指定轴的最大值。
numpy.amax(a, axis=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)# 参数说明:# a: 输入的数组,可以是一个NumPy数组或类似数组的对象。# axis: 可选参数,用于指定在哪个轴上计算最大值。如果不提供此参数,则返回整个数组的最大值。可以是一个整数表示轴的索引,也可以是一个元组表示多个轴。# out: 可选参数,用于指定结果的存储位置。# keepdims: 可选参数,如果为True,将保持结果数组的维度数目与输入数组相同。如果为False(默认值),则会去除计算后维度为1的轴。# initial: 可选参数,用于指定一个初始值,然后在数组的元素上计算最大值。# where: 可选参数,一个布尔数组,用于指定仅考虑满足条件的元素。import numpy as npa = np.array([[3,7,5],[8,4,3],[2,4,9]])print ('我们的数组是:')print (a)print ('\\n')print ('调用 amin() 函数:')print (np.amin(a,1))print ('\\n')print ('再次调用 amin() 函数:')print (np.amin(a,0))print ('\\n')print ('调用 amax() 函数:')print (np.amax(a))print ('\\n')print ('再次调用 amax() 函数:')print (np.amax(a, axis = 0)) -
numpy.ptp()
numpy.ptp() 函数计算数组中元素最大值与最小值的差(最大值 - 最小值)。
numpy.ptp(a,axis=None,out=None,keepdims=<no value>,initial=<no value>,where=<no value>)# 参数说明:# a: 输入的数组,可以是一个 NumPy 数组或类似数组的对象。# axis: 可选参数,用于指定在哪个轴上计算峰-峰值。如果不提供此参数,则返回整个数组的峰-峰值。可以是一个整数表示轴的索引,也可以是一个元组表示多个轴。# out: 可选参数,用于指定结果的存储位置。# keepdims: 可选参数,如果为 True,将保持结果数组的维度数目与输入数组相同。如果为 False(默认值),则会去除计算后维度为1的轴。# initial: 可选参数,用于指定一个初始值,然后在数组的元素上计算峰-峰值。# where: 可选参数,一个布尔数组,用于指定仅考虑满足条件的元素。import numpy as npa = np.array([[3,7,5],[8,4,3],[2,4,9]])print ('我们的数组是:')print (a)print ('\\n')print ('调用 ptp() 函数:')print (np.ptp(a))print ('\\n')print ('沿轴 1 调用 ptp() 函数:')print (np.ptp(a, axis = 1))print ('\\n')print ('沿轴 0 调用 ptp() 函数:')print (np.ptp(a, axis = 0)) -
numpy.percentile()
百分位数是统计中使用的度量,表示小于这个值的观察值的百分比。 函数numpy.percentile()接受以下参数。
首先明确百分位数:
第 p 个百分位数是这样一个值,它使得至少有 p% 的数据项小于或等于这个值,且至少有 (100-p)% 的数据项大于或等于这个值。
举个例子:高等院校的入学考试成绩经常以百分位数的形式报告。比如,假设某个考生在入学考试中的语文部分的原始分数为 54 分。相对于参加同一考试的其他学生来说,他的成绩如何并不容易知道。但是如果原始分数54分恰好对应的是第70百分位数,我们就能知道大约70%的学生的考分比他低,而约30%的学生考分比他高。
这里的 p = 70。numpy.percentile(a, q, axis)# 参数说明:# a: 输入数组# q: 要计算的百分位数,在 0 ~ 100 之间# axis: 沿着它计算百分位数的轴import numpy as npa = np.array([[10, 7, 4], [3, 2, 1]])print ('我们的数组是:')print (a)print ('调用 percentile() 函数:')# 50% 的分位数,就是 a 里排序之后的中位数print (np.percentile(a, 50))# axis 为 0,在纵列上求print (np.percentile(a, 50, axis=0))# axis 为 1,在横行上求print (np.percentile(a, 50, axis=1))# 保持维度不变print (np.percentile(a, 50, axis=1, keepdims=True)) -
numpy.median()
numpy.median() 函数用于计算数组 a 中元素的中位数(中值)
numpy.median(a, axis=None, out=None, overwrite_input=False, keepdims=<no value>)# 参数说明:# a: 输入的数组,可以是一个 NumPy 数组或类似数组的对象。# axis: 可选参数,用于指定在哪个轴上计算中位数。如果不提供此参数,则计算整个数组的中位数。可以是一个整数表示轴的索引,也可以是一个元组表示多个轴。# out: 可选参数,用于指定结果的存储位置。# overwrite_input: 可选参数,如果为True,则允许在计算中使用输入数组的内存。这可能会在某些情况下提高性能,但可能会修改输入数组的内容。# keepdims: 可选参数,如果为True,将保持结果数组的维度数目与输入数组相同。如果为False(默认值),则会去除计算后维度为1的轴。import numpy as npa = np.array([[30,65,70],[80,95,10],[50,90,60]])print ('我们的数组是:')print (a)print ('\\n')print ('调用 median() 函数:')print (np.median(a))print ('\\n')print ('沿轴 0 调用 median() 函数:')print (np.median(a, axis = 0))print ('\\n')print ('沿轴 1 调用 median() 函数:')print (np.median(a, axis = 1)) -
numpy.mean()
numpy.mean() 函数返回数组中元素的算术平均值,如果提供了轴,则沿其计算。
算术平均值是沿轴的元素的总和除以元素的数量。
numpy.mean(a, axis=None, dtype=None, out=None, keepdims=<no value>)# 参数说明:# a: 输入的数组,可以是一个 NumPy 数组或类似数组的对象。# axis: 可选参数,用于指定在哪个轴上计算平均值。如果不提供此参数,则计算整个数组的平均值。可以是一个整数表示轴的索引,也可以是一个元组表示多个轴。# dtype: 可选参数,用于指定输出的数据类型。如果不提供,则根据输入数据的类型选择合适的数据类型。# out: 可选参数,用于指定结果的存储位置。# keepdims: 可选参数,如果为True,将保持结果数组的维度数目与输入数组相同。如果为False(默认值),则会去除计算后维度为1的轴。 -
numpy.average()
numpy.average() 函数根据在另一个数组中给出的各自的权重计算数组中元素的加权平均值。
该函数可以接受一个轴参数。 如果没有指定轴,则数组会被展开。
加权平均值即将各数值乘以相应的权数,然后加总求和得到总体值,再除以总的单位数。
numpy.average(a, axis=None, weights=None, returned=False)# 参数说明:# a: 输入的数组,可以是一个 NumPy 数组或类似数组的对象。# axis: 可选参数,用于指定在哪个轴上计算加权平均值。如果不提供此参数,则计算整个数组的加权平均值。可以是一个整数表示轴的索引,也可以是一个元组表示多个轴。# weights: 可选参数,用于指定对应数据点的权重。如果不提供权重数组,则默认为等权重。# returned: 可选参数,如果为True,将同时返回加权平均值和权重总和。 -
numpy.average()
numpy.average() 函数根据在另一个数组中给出的各自的权重计算数组中元素的加权平均值。
该函数可以接受一个轴参数。 如果没有指定轴,则数组会被展开。
加权平均值即将各数值乘以相应的权数,然后加总求和得到总体值,再除以总的单位数。
numpy.average(a, axis=None, weights=None, returned=False)# 参数说明:# a: 输入的数组,可以是一个 NumPy 数组或类似数组的对象。# axis: 可选参数,用于指定在哪个轴上计算加权平均值。如果不提供此参数,则计算整个数组的加权平均值。可以是一个整数表示轴的索引,也可以是一个元组表示多个轴。# weights: 可选参数,用于指定对应数据点的权重。如果不提供权重数组,则默认为等权重。# returned: 可选参数,如果为True,将同时返回加权平均值和权重总和。import numpy as npa = np.array([1,2,3,4])print ('我们的数组是:')print (a)print ('\\n')print ('调用 average() 函数:')print (np.average(a))print ('\\n')# 不指定权重时相当于 mean 函数wts = np.array([4,3,2,1])print ('再次调用 average() 函数:')print (np.average(a,weights = wts))print ('\\n')# 如果 returned 参数设为 true,则返回权重的和print ('权重的和:')print (np.average([1,2,3, 4],weights = [4,3,2,1], returned = True))# 在多维数组中,可以指定用于计算的轴。a = np.arange(6).reshape(3,2)print ('我们的数组是:')print (a)print ('\\n')print ('修改后的数组:')wt = np.array([3,5])print (np.average(a, axis = 1, weights = wt))print ('\\n')print ('修改后的数组:')print (np.average(a, axis = 1, weights = wt, returned = True)) -
标准差
标准差是一组数据平均值分散程度的一种度量。
标准差是方差的算术平方根。
标准差公式如下:
std = sqrt(mean((x - x.mean())^2))import numpy as npprint (np.std([1,2,3,4])) -
方差
统计中的方差(样本方差)是每个样本值与全体样本值的平均数之差的平方值的平均数,即 mean((x - x.mean())** 2)。
换句话说,标准差是方差的平方根。
import numpy as npprint (np.var([1,2,3,4]))
NumPy 排序、条件筛选函数
NumPy 提供了多种排序的方法。 这些排序函数实现不同的排序算法,每个排序算法的特征在于执行速度,最坏情况性能,所需的工作空间和算法的稳定性。 下表显示了三种排序算法的比较。
| 种类 | 速度 | 最坏情况 | 工作空间 | 稳定性 |
|---|---|---|---|---|
| ’quicksort’(快速排序) | 1 | O(n^2) | O(1) | 否 |
| ’mergesort’(归并排序) | 2 | O(n * log(n)) | O(n) | 是 |
| ’heapsort’(堆排序) | 3 | O(n*log(n)) | O(1) | 否 |
-
numpy.sort()
numpy.sort() 函数返回输入数组的排序副本。函数格式如下:
numpy.sort(a, axis, kind, order)# 参数说明:# a: 要排序的数组# axis: 沿着它排序数组的轴,如果没有数组会被展开,沿着最后的轴排序, axis=0 按列排序,axis=1 按行排序# kind: 默认为'quicksort'(快速排序)# order: 如果数组包含字段,则是要排序的字段 -
numpy.argsort()
numpy.argsort() 函数返回的是数组值从小到大的索引值。
import numpy as npx = np.array([3, 1, 2])print ('我们的数组是:')print (x)print ('\\n')print ('对 x 调用 argsort() 函数:')y = np.argsort(x)print (y)print ('\\n')print ('以排序后的顺序重构原数组:')print (x[y]) -
numpy.lexsort()
numpy.lexsort() 用于对多个序列进行排序。把它想象成对电子表格进行排序,每一列代表一个序列,排序时优先照顾靠后的列。
import numpy as npnm = ('raju','anil','ravi','amar')dv = ('f.y.', 's.y.', 's.y.', 'f.y.')ind = np.lexsort((dv,nm))print ('调用 lexsort() 函数:')print (ind)print ('\\n')print ('使用这个索引来获取排序后的数据:')print ([nm[i] + ", " + dv[i] for i in ind]) -
msort、sort_complex、partition、argpartition
函数 描述 msort(a) 数组按第一个轴排序,返回排序后的数组副本。np.msort(a) 相等于 np.sort(a, axis=0)。 sort_complex(a) 对复数按照先实部后虚部的顺序进行排序。 partition(a, kth[, axis, kind, order]) 指定一个数,对数组进行分区 argpartition(a, kth[, axis, kind, order]) 可以通过关键字 kind 指定算法沿着指定轴对数组进行分区 -
numpy.argmax() 和 numpy.argmin()
numpy.argmax() 和 numpy.argmin()函数分别沿给定轴返回最大和最小元素的索引。
-
numpy.nonzero()
numpy.nonzero() 函数返回输入数组中非零元素的索引。
-
numpy.where()
numpy.where() 函数返回输入数组中满足给定条件的元素的索引。
-
numpy.extract()
numpy.extract() 函数根据某个条件从数组中抽取元素,返回满条件的元素。
NumPy 字节交换
在几乎所有的机器上,多字节对象都被存储为连续的字节序列。字节顺序,是跨越多字节的程序对象的存储规则。
- 大端模式:指数据的高字节保存在内存的低地址中,而数据的低字节保存在内存的高地址中,这样的存储模式有点儿类似于把数据当作字符串顺序处理:地址由小向大增加,而数据从高位往低位放;这和我们的阅读习惯一致。
- 小端模式:指数据的高字节保存在内存的高地址中,而数据的低字节保存在内存的低地址中,这种存储模式将地址的高低和数据位权有效地结合起来,高地址部分权值高,低地址部分权值低。
numpy.ndarray.byteswap() 函数将 ndarray 中每个元素中的字节进行大小端转换。
import numpy as np
A = np.array([1, 256, 8755], dtype=np.int16)print(A)print(list(map(hex, A)))print(A.byteswap(inplace=True))print(list(map(hex, A)))Numpy 副本和视图
副本是一个数据的完整的拷贝,如果我们对副本进行修改,它不会影响到原始数据,物理内存不在同一位置。
视图是数据的一个别称或引用,通过该别称或引用亦便可访问、操作原有数据,但原有数据不会产生拷贝。如果我们对视图进行修改,它会影响到原始数据,物理内存在同一位置。
视图一般发生在:
- numpy 的切片操作返回原数据的视图。
- 调用 ndarray 的 view() 函数产生一个视图。
副本一般发生在:
- Python 序列的切片操作,调用deepCopy()函数。
- 调用 ndarray 的 copy() 函数产生一个副本。
无复制
简单的赋值不会创建数组对象的副本。 相反,它使用原始数组的相同id()来访问它。 id()返回 Python 对象的通用标识符,类似于 C 中的指针。
此外,一个数组的任何变化都反映在另一个数组上。 例如,一个数组的形状改变也会改变另一个数组的形状。
import numpy as np
a = np.arange(6)print ('我们的数组是:')print (a)print ('调用 id() 函数:')print (id(a))print ('a 赋值给 b:')b = aprint (b)print ('b 拥有相同 id():')print (id(b))print ('修改 b 的形状:')b.shape = 3,2print (b)print ('a 的形状也修改了:')print (a)视图或浅拷贝
ndarray.view() 方会创建一个新的数组对象,该方法创建的新数组的维数变化不会改变原始数据的维数。
import numpy as np
# 最开始 a 是个 3X2 的数组a = np.arange(6).reshape(3,2)print ('数组 a:')print (a)print ('创建 a 的视图:')b = a.view()print (b)print ('两个数组的 id() 不同:')print ('a 的 id():')print (id(a))print ('b 的 id():' )print (id(b))# 修改 b 的形状,并不会修改 ab.shape = 2,3print ('b 的形状:')print (b)print ('a 的形状:')print (a)
# 使用切片创建视图修改数据会影响到原始数组:arr = np.arange(12)print ('我们的数组:')print (arr)print ('创建切片:')a=arr[3:]b=arr[3:]a[1]=123b[2]=234print(arr)print(id(a),id(b),id(arr[3:]))副本或深拷贝
ndarray.copy() 函数创建一个副本。 对副本数据进行修改,不会影响到原始数据,它们物理内存不在同一位置。
import numpy as np
a = np.array([[10,10], [2,3], [4,5]])print ('数组 a:')print (a)print ('创建 a 的深层副本:')b = a.copy()print ('数组 b:')print (b)# b 与 a 不共享任何内容print ('我们能够写入 b 来写入 a 吗?')print (b is a)print ('修改 b 的内容:')b[0,0] = 100print ('修改后的数组 b:')print (b)print ('a 保持不变:')print (a)Numpy矩阵库
NumPy 中包含了一个矩阵库 numpy.matlib,该模块中的函数返回的是一个矩阵,而不是 ndarray 对象。
一个 的矩阵是一个由行(row)列(column)元素排列成的矩形阵列。
矩阵里的元素可以是数字、符号或数学式。
转置矩阵
NumPy 中除了可以使用 numpy.transpose 函数来对换数组的维度,还可以使用 T 属性。。
例如有个 m 行 n 列的矩阵,使用 t() 函数就能转换为 n 行 m 列的矩阵。

import numpy as np
a = np.arange(12).reshape(3,4)
print ('原数组:')print (a)print ('\\n')
print ('转置数组:')print (a.T)matlib.empty()
matlib.empty() 函数返回一个新的矩阵,语法格式为:
numpy.matlib.empty(shape, dtype, order)
# 参数说明:# shape: 定义新矩阵形状的整数或整数元组# Dtype: 可选,数据类型# order: C(行序优先) 或者 F(列序优先)
import numpy.matlibimport numpy as np
print (np.matlib.empty((2,2)))# 填充为随机数据numpy.matlib.zeros()
numpy.matlib.zeros() 函数创建一个以 0 填充的矩阵。
import numpy as np
print (np.matlib.zeros((2,2)))numpy.matlib.ones()
numpy.matlib.ones()函数创建一个以 1 填充的矩阵。
import numpy.matlibimport numpy as np
print (np.matlib.ones((2,2)))numpy.matlib.eye()
numpy.matlib.eye() 函数返回一个矩阵,对角线元素为 1,其他位置为零。
numpy.matlib.eye(n, M,k, dtype)
# 参数说明:# n: 返回矩阵的行数# M: 返回矩阵的列数,默认为 n# k: 对角线的索引# dtype: 数据类型
import numpy.matlibimport numpy as np
print (np.matlib.eye(n = 3, M = 4, k = 0, dtype = float))numpy.matlib.identity()
numpy.matlib.identity() 函数返回给定大小的单位矩阵。
单位矩阵是个方阵,从左上角到右下角的对角线(称为主对角线)上的元素均为 1,除此以外全都为 0。
import numpy.matlibimport numpy as np
# 大小为 5,类型位浮点型print (np.matlib.identity(5, dtype = float))numpy.matlib.rand()
numpy.matlib.rand() 函数创建一个给定大小的矩阵,数据是随机填充的。
import numpy.matlibimport numpy as np
print (np.matlib.rand(3,3))
# 矩阵总是二维的,而 ndarray 是一个 n 维数组。 两个对象都是可互换的。import numpy.matlibimport numpy as np
i = np.matrix('1,2;3,4')print (i)
j = np.asarray(i)print (j)
k = np.asmatrix (j)print (k)Numpy线性代数
NumPy 提供了线性代数函数库 linalg,该库包含了线性代数所需的所有功能,可以看看下面的说明:
| 函数 | 描述 | 函数 |
|---|---|---|
| dot | 两个数组的点积,即元素对应相乘。 | numpy.dot(a, b, out=None) |
| vdot | 两个向量的点积。如果第一个参数是复数,那么它的共轭复数会用于计算。 如果参数是多维数组,它会被展开 | numpy.vdot(a, b) |
| inner | 返回一维数组的向量内积。对于更高的维度,它返回最后一个轴上的和的乘积 | numpy.vdot(a, b) |
| matmul | 两个数组的矩阵积 | numpy.inner(a, b) |
| determinant | 数组的行列式 | numpy.det(a, b) |
| solve | 求解线性矩阵方程 | numpy.solve(a, b) |
| inv | 计算矩阵的乘法逆矩阵 | numpy.inv(a) |
-
matmul
numpy.matmul 函数返回两个数组的矩阵乘积。 虽然它返回二维数组的正常乘积,但如果任一参数的维数大于2,则将其视为存在于最后两个索引的矩阵的栈,并进行相应广播。
另一方面,如果任一参数是一维数组,则通过在其维度上附加 1 来将其提升为矩阵,并在乘法之后被去除。
对于二维数组,它就是矩阵乘法:
import numpy.matlibimport numpy as npa = [[1,0],[0,1]]b = [[4,1],[2,2]]print (np.matmul(a,b))# 二维和一维运算a = [[1,0],[0,1]]b = [1,2]print (np.matmul(a,b))print (np.matmul(b,a))# 维度大于二的数组a = np.arange(8).reshape(2,2,2)b = np.arange(4).reshape(2,2)print (np.matmul(a,b))
Numpy IO
Numpy 可以读写磁盘上的文本数据或二进制数据。
NumPy 为 ndarray 对象引入了一个简单的文件格式:npy。
npy 文件用于存储重建 ndarray 所需的数据、图形、dtype 和其他信息。
常用的 IO 函数有:
- load() 和 save() 函数是读写文件数组数据的两个主要函数,默认情况下,数组是以未压缩的原始二进制格式保存在扩展名为 .npy 的文件中。
- savez() 函数用于将多个数组写入文件,默认情况下,数组是以未压缩的原始二进制格式保存在扩展名为 .npz 的文件中。
- oadtxt() 和 savetxt() 函数处理正常的文本文件(.txt 等)
-
numpy.save()
numpy.save() 函数将数组保存到以 .npy 为扩展名的文件中。
numpy.save(file, arr, allow_pickle=True, fix_imports=True) -
np.savez
numpy.savez() 函数将多个数组保存到以 npz 为扩展名的文件中。
numpy.savez(file, *args, **kwds) -
savetxt()
savetxt() 函数是以简单的文本文件格式存储数据,对应的使用 loadtxt() 函数来获取数据。
np.loadtxt(FILENAME, dtype=int, delimiter=' ')np.savetxt(FILENAME, a, fmt="%d", delimiter=",")参数 delimiter 可以指定各种分隔符、针对特定列的转换器函数、需要跳过的行数等。
Numpy + Matplotlib
Matplotlib是Python的绘图库。 它可与NumPy一起使用,提供了一种有效的 MatLab开源替代方案。它也可以和图形工具包一起使用,如PyQt和wxPython。
pip3 安装:
pip3 install matplotlib
# 安装验证pip3 list | grep matplotlib使用:
import numpy as npfrom matplotlib import pyplot as plt
x = np.arange(1,11)y = 2 * x + 5plt.title("Matplotlib demo")plt.xlabel("x axis caption")plt.ylabel("y axis caption")plt.plot(x,y)plt.show()中文使用
Matplotlib 默认情况不支持中文,我们可以使用以下简单的方法来解决。
- 下载 思源黑体
- 把下载的OTF字体放到代码文件下即可
matplotlib.font_manager.FontProperties(fname="SourceHanSansSC-Bold.otf")fname指定字体库路径
import numpy as npfrom matplotlib import pyplot as pltimport matplotlib
# fname 为 你下载的字体库路径,注意 SourceHanSansSC-Bold.otf 字体的路径zhfont1 = matplotlib.font_manager.FontProperties(fname="SourceHanSansSC-Bold.otf")
x = np.arange(1,11)y = 2 * x + 5plt.title("菜鸟教程 - 测试", fontproperties=zhfont1)
# fontproperties 设置中文显示,fontsize 设置字体大小plt.xlabel("x 轴", fontproperties=zhfont1)plt.ylabel("y 轴", fontproperties=zhfont1)plt.plot(x,y)plt.show()
NumPy Calculations
NumPy Bitwise Operations
Bitwise operations are a class of operations that perform on binary numbers at the bit level, directly manipulating the individual bits of binary representations without regard to the overall value.
Bitwise operations are widely used in computer science for optimization and handling of low-level data.
NumPy “bitwise_” prefixed functions are bitwise operation functions.
NumPy bitwise operations include the following functions:
| Function | Description | Operator |
|---|---|---|
| bitwise_and | Bitwise AND, performs the AND operation on array elements | & |
| bitwise_or | Bitwise OR, performs the OR operation on array elements | |
| bitwise_xor | Bitwise XOR | ^ |
| bitwise_not | Bitwise NOT | ~ |
| invert | Bitwise NOT | ~ |
| left_shift | Left shift, shifts the binary representation to the left by bits | << |
| right_shift | Right shift, shifts the binary representation to the right by bits | >> |
import numpy as np
arr1 = np.array([True, False, True], dtype=bool)arr2 = np.array([False, True, False], dtype=bool)
result_and = np.bitwise_and(arr1, arr2)result_or = np.bitwise_or(arr1, arr2)result_xor = np.bitwise_xor(arr1, arr2)result_not = np.bitwise_not(arr1)
print("AND:", result_and) # [False, False, False]print("OR:", result_or) # [True, True, True]print("XOR:", result_xor) # [True, True, True]print("NOT:", result_not) # [False, True, False]
# Bitwise NOTarr_invert = np.invert(np.array([1, 2], dtype=np.int8))print("Invert:", arr_invert) # [-2, -3]
# Left shiftarr_left_shift = np.left_shift(5, 2)print("Left Shift:", arr_left_shift) # 20
# Right shiftarr_right_shift = np.right_shift(10, 1)print("Right Shift:", arr_right_shift) # 5String Functions
The following functions operate on arrays with dtype numpy.string_ or numpy.unicode_ to perform vectorized string operations. They are based on the standard string functions in the Python standard library.
These functions are defined in the character array class (numpy.char).
| Function | Description |
|---|---|
| add() | Concatenates corresponding elements of two arrays of strings |
| multiply() | Returns the strings formed by element-wise repetition |
| center() | Centers the string, padding with a specified character on the left and right |
| capitalize() | Converts the first letter of the string to uppercase |
| title() | Converts the first letter of each word in the string to uppercase |
| lower() | Converts array elements to lowercase |
| upper() | Converts array elements to uppercase |
| split() | Splits strings by a specified separator and returns a list of arrays |
| splitlines() | Returns a list of lines in each element, splitting on newline |
| strip() | Removes specified characters from the start or end of elements |
| join() | Joins elements in the array into a single string using a separator |
| replace() | Replaces all substrings in the string with a new string |
| decode() | Calls str.decode on each array element |
| encode() | Calls str.encode on each array element |
- numpy.char.add()/multiply()/center()
The numpy.char.add() function concatenates the elements of two arrays element-wise.
import numpy as np
print ('Concatenating two strings:')print (np.char.add(['hello'],[' xyz']))print ('\\n')
print ('Concatenation examples:')print (np.char.add(['hello', 'hi'],[' abc', ' xyz']))
print (np.char.multiply('Runoob ',3))
# np.char.center(str , width,fillchar) :# str: string, width: length, fillchar: fill characterprint (np.char.center('Runoob', 20,fillchar = '*'))- numpy.char.capitalize()/title()/lower()/upper()
import numpy as np
print (np.char.capitalize('runoob'))
print (np.char.capitalize('runoob'))
# operate on arraysprint (np.char.lower(['RUNOOB','GOOGLE']))
# operate on stringsprint (np.char.lower('RUNOOB'))- numpy.char.split()/splitlines()/strip()
numpy.char.split() splits strings by a specified separator and returns an array. By default, the separator is a space.
import numpy as np
# Separator defaults to spaceprint (np.char.split ('i like runoob?'))# Separator is .print (np.char.split ('www.runoob.com', sep = '.'))
# Newline characters \\n# \\n, \\r, \\r\\n can all be used as line breaks.print (np.char.splitlines('i\\nlike runoob?'))print (np.char.splitlines('i\\rlike runoob?'))
# Remove the leading and trailing 'a' from the stringprint (np.char.strip('ashok arunooba','a'))
# Remove the leading and trailing 'a' from array elementsprint (np.char.strip(['arunooba','admin','java'],'a'))- numpy.char.join()/replace()/encode()/decode()
numpy.char.join() function joins the elements of an array or strings using a specified separator.
import numpy as np
# operate on stringsprint (np.char.join(':','runoob'))
# operate on multiple separators for array elementsprint (np.char.join([':','-'],['runoob','google']))
print (np.char.replace ('i like runoob', 'oo', 'cc'))
a = np.char.encode('runoob', 'cp500')print (a)
print (np.char.decode(a,'cp500'))NumPy Mathematical Functions
Trigonometric Functions
NumPy provides the standard trigonometric functions: sin(), cos(), tan().
import numpy as np
a = np.array([0,30,45,60,90])print ('Sine values for different angles:')# Convert to radians by multiplying pi/180print (np.sin(a*np.pi/180))print ('\\n')print ('Cosine values for angles in the array:')print (np.cos(a*np.pi/180))print ('\\n')print ('Tangent values for angles in the array:')print (np.tan(a*np.pi/180))arcsin, arccos, and arctan functions return the inverse trigonometric functions of sin, cos and tan for given angles.
These function results can be converted from radians to degrees using numpy.degrees().
import numpy as np
a = np.array([0,30,45,60,90])print ('Array with sine values:')sin = np.sin(a*np.pi/180)print (sin)print ('\\n')print ('Inverse sine of the angles, result in radians:')inv = np.arcsin(sin)print (inv)print ('\\n')print ('Check the result by converting back to degrees:')print (np.degrees(inv))print ('\\n')print ('Inverse cosine and arctan behave similarly:')cos = np.cos(a*np.pi/180)print (cos)print ('\\n')print ('Arccosine:')inv = np.arccos(cos)print (inv)print ('\\n')print ('Angle in degrees:')print (np.degrees(inv))print ('\\n')print ('Tangent:')tan = np.tan(a*np.pi/180)print (tan)print ('\\n')print ('Inverse tangent:')inv = np.arctan(tan)print (inv)print ('\\n')print ('Angle in degrees:')print (np.degrees(inv))Rounding Functions
-
numpy.around() The function returns the rounded value of the given number.
# numpy.around(a,decimals)# a: array# decimals: number of decimals to round to. Default is 0. If negative, round to the left of the decimal pointimport numpy as npa = np.array([1.0,5.55, 123, 0.567, 25.532])print ('Original array:')print (a)print ('\\n')print ('Rounded:')print (np.around(a))print (np.around(a, decimals = 1))print (np.around(a, decimals = -1)) -
numpy.floor() Returns the largest integer less than or equal to the given expression, i.e., floor.
import numpy as npa = np.array([-1.7, 1.5, -0.2, 0.6, 10])print ('Provided array:')print (a)print ('\\n')print ('Modified array:')print (np.floor(a)) -
numpy.ceil() Returns the smallest integer greater than or equal to the given expression, i.e., ceil.
import numpy as npa = np.array([-1.7, 1.5, -0.2, 0.6, 10])print ('Provided array:')print (a)print ('\\n')print ('Modified array:')print (np.ceil(a))
Arithmetic Functions
NumPy arithmetic functions include simple addition, subtraction, multiplication, and division: add(), subtract(), multiply() and divide().
Note that arrays must have the same shape or be broadcastable.
import numpy as np
a = np.arange(9, dtype = np.float_).reshape(3,3)print ('First array:')print (a)print ('\\n')print ('Second array:')b = np.array([10,10,10])print (b)print ('\\n')print ('Addition of the two arrays:')print (np.add(a,b))print ('\\n')print ('Subtraction of the two arrays:')print (np.subtract(a,b))print ('\\n')print ('Multiplication of the two arrays:')print (np.multiply(a,b))print ('\\n')print ('Division of the two arrays:')print (np.divide(a,b))-
numpy.reciprocal()
numpy.reciprocal() returns the reciprocal of each element in the input array. For example, the reciprocal of 1/4 is 4/1.
import numpy as npa = np.array([0.25, 1.33, 1, 100])print ('Our array:')print (a)print ('\\n')print ('Calling reciprocal function:')print (np.reciprocal(a)) -
numpy.power()
numpy.power() takes the elements in the first input array as bases and raises them to the powers of the corresponding elements in the second input array.
import numpy as npa = np.array([10,100,1000])print ('Our array:')print (a)print ('\\n')print ('Calling power function:')print (np.power(a,2))print ('\\n')print ('Second array:')b = np.array([1,2,3])print (b)print ('\\n')print ('Calling power function again:')print (np.power(a,b)) -
numpy.mod()
numpy.mod() computes the remainder after division for corresponding elements in the input arrays. The
numpy.remainder()function produces the same result.import numpy as npa = np.array([10,20,30])b = np.array([3,5,7])print ('First array:')print (a)print ('\\n')print ('Second array:')print (b)print ('\\n')print ('Calling mod() function:')print (np.mod(a,b))print ('\\n')print ('Calling remainder() function:')print (np.remainder(a,b))
Statistical Functions
-
numpy.amin() and numpy.amax()
numpy.amin() is used to compute the minimum value of elements in an array along a specified axis.
numpy.amin(a, axis=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)# Parameter descriptions:# a: input array, can be a NumPy array or array-like object.# axis: optional parameter to specify along which axis to compute the minimum. If not provided, returns the minimum of the entire array. Can be an integer or a tuple of axes.# out: optional parameter for the output storage.# keepdims: optional parameter; if True, keeps the number of dimensions of the result the same as input. If False (default), reduces axes of length 1.# initial: optional parameter to specify an initial value for the minimum calculation.# where: optional boolean array to specify which elements to consider.numpy.amax() is used to compute the maximum value along a specified axis of the array.
numpy.amax(a, axis=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)# Parameter descriptions:# a: input array, can be a NumPy array or array-like object.# axis: optional parameter to specify along which axis to compute the maximum. If not provided, returns the maximum of the entire array. Can be an integer or a tuple of axes.# out: optional parameter for the output storage.# keepdims: optional parameter; if True, keeps the number of dimensions of the result the same as input. If False (default), reduces axes of length 1.# initial: optional parameter to specify an initial value for the maximum calculation.# where: optional boolean array to specify which elements to consider.
import numpy as np
a = np.array([[3,7,5],[8,4,3],[2,4,9]])print ('Our array is:')print (a)print ('\\n')print ('Calling amin() function:')print (np.amin(a,1))print ('\\n')print ('Calling amin() again:')print (np.amin(a,0))print ('\\n')print ('Calling amax() function:')print (np.amax(a))print ('\\n')print ('Calling amax() again:')print (np.amax(a, axis = 0))-
numpy.ptp()
numpy.ptp() computes the difference between the maximum and minimum values in the array (max - min).
numpy.ptp(a,axis=None,out=None,keepdims=<no value>,initial=<no value>,where=<no value>)# Parameter descriptions:# a: input array, can be a NumPy array or array-like object.# axis: optional parameter; specify axis for peak-to-peak value. If not provided, returns the peak-to-peak of the entire array. Can be an integer or a tuple of axes.# out: optional parameter for the output storage.# keepdims: optional parameter; if True, keeps the dimensions. If False (default), reduces axes of length 1.# initial: optional parameter for an initial value.# where: optional boolean array to specify which elements to consider.import numpy as npa = np.array([[3,7,5],[8,4,3],[2,4,9]])print ('Our array:')print (a)print ('\\n')print ('Calling ptp() function:')print (np.ptp(a))print ('\\n')print ('Along axis 1:')print (np.ptp(a, axis = 1))print ('\\n')print ('Along axis 0:')print (np.ptp(a, axis = 0)) -
numpy.percentile()
Percentiles are metrics used in statistics that indicate the percentage of observations below this value. The function numpy.percentile() accepts the following parameters.
First, the percentile:
The p-th percentile is a value such that at least p% of the data items are less than or equal to this value, and at least (100-p)% are greater than or equal to this value.
For example, college entrance exam results are often reported in percentiles. Suppose a candidate’s raw score in the Chinese section is 54. Relative to others, it is not easy to judge. But if a raw score of 54 corresponds to the 70th percentile, we know about 70% of students scored below him and about 30% scored above him.
Here p = 70.
numpy.percentile(a, q, axis)
# Parameter descriptions:# a: input array# q: percentiles to compute, in the range 0 ~ 100# axis: axis along which to compute the percentiles
import numpy as np
a = np.array([[10, 7, 4], [3, 2, 1]])print ('Our array:')print (a)
print ('Calling percentile() function:')# 50% percentile is the median of a after sortingprint (np.percentile(a, 50))
# axis 0, along columnsprint (np.percentile(a, 50, axis=0))
# axis 1, along rowsprint (np.percentile(a, 50, axis=1))
# keep dimensionsprint (np.percentile(a, 50, axis=1, keepdims=True))-
numpy.median()
numpy.median() is used to compute the median of the elements in array
a.numpy.median(a, axis=None, out=None, overwrite_input=False, keepdims=<no value>)# Parameter descriptions:# a: input array, can be a NumPy array or array-like object.# axis: optional parameter to specify along which axis to compute the median. If not provided, computes the median of the entire array. Can be an integer or a tuple of axes.# out: optional parameter for the output storage.# overwrite_input: optional parameter; if True, allows using the input array's memory in the computation. This may improve performance in some cases, but may modify the input array.# keepdims: optional parameter; if True, keeps the dimensionality of the result the same as the input array. If False (default), reduces axes of length 1.import numpy as npa = np.array([[30,65,70],[80,95,10],[50,90,60]])print ('Our array:')print (a)print ('\\n')print ('Calling median() function:')print (np.median(a))print ('\\n')print ('Along axis 0:')print (np.median(a, axis = 0))print ('\\n')print ('Along axis 1:')print (np.median(a, axis = 1)) -
numpy.mean()
numpy.mean() returns the arithmetic mean of the elements in the array. If an axis is provided, it computes along that axis.
The arithmetic mean is the sum of the elements along the axis divided by the number of elements.
numpy.mean(a, axis=None, dtype=None, out=None, keepdims=<no value>)# Parameter descriptions:# a: input array, can be a NumPy array or array-like object.# axis: optional parameter to specify along which axis to compute the mean. If not provided, computes the mean of the entire array. Can be an integer or a tuple of axes.# dtype: optional parameter to specify the output data type. If not provided, an appropriate dtype is chosen based on the input data.# out: optional parameter to specify the output storage.# keepdims: optional parameter; if True, keeps the dimensions of the result the same as the input; if False (default), reduces axes of length 1. -
numpy.average()
numpy.average() computes the weighted average of array elements using the corresponding weights provided in another array.
This function can accept an
axisparameter. If no axis is specified, the array is flattened.A weighted average is obtained by multiplying each value by its corresponding weight, summing them, and dividing by the total weight.
numpy.average(a, axis=None, weights=None, returned=False)# Parameter descriptions:# a: input array, can be a NumPy array or array-like object.# axis: optional parameter to specify along which axis to compute the weighted average. If not provided, computes the weighted average of the entire array. Can be an integer or a tuple of axes.# weights: optional parameter to specify the weights for data points. If weights are not provided, equal weights are assumed.# returned: optional parameter; if True, returns the weighted average and the sum of weights.import numpy as npa = np.array([1,2,3,4])print ('Our array:')print (a)print ('\\n')print ('Calling average() function:')print (np.average(a))print ('\\n')# If weights are not specified, equivalent to meanwts = np.array([4,3,2,1])print ('Calling average() again:')print (np.average(a,weights = wts))print ('\\n')# If returned is true, also return the sum of weightsprint ('Sum of weights:')print (np.average([1,2,3, 4],weights = [4,3,2,1], returned = True))# In a multi-dimensional array, you can specify the axis to compute on.a = np.arange(6).reshape(3,2)print ('Our array:')print (a)print ('\\n')print ('Modified array:')wt = np.array([3,5])print (np.average(a, axis = 1, weights = wt))print ('\\n')print ('Modified array:')print (np.average(a, axis = 1, weights = wt, returned = True)) -
Standard Deviation
Standard deviation is a measure of the dispersion of a set of data around its mean.
The standard deviation is the square root of the variance.
std = sqrt(mean((x - x.mean())^2))import numpy as npprint (np.std([1,2,3,4])) -
Variance
The variance (sample variance) in statistics is the average of the squared differences between each sample value and the mean of all samples, i.e., mean((x - x.mean())** 2).
In other words, the standard deviation is the square root of the variance.
import numpy as npprint (np.var([1,2,3,4]))
NumPy Sorting and Filtering Functions
NumPy provides several sorting methods. These sorting functions implement different sorting algorithms, each characterized by speed, worst-case performance, required workspace, and stability. The table below compares three sorting algorithms.
| Kind | Speed | Worst case | Workspace | Stability |
|---|---|---|---|---|
| ’quicksort’ (Quicksort) | 1 | O(n^2) | O(1) | No |
| ’mergesort’ (Merge Sort) | 2 | O(n * log(n)) | O(n) | Yes |
| ’heapsort’ (Heap Sort) | 3 | O(n*log(n)) | O(1) | No |
-
numpy.sort()
numpy.sort() function returns a sorted copy of the input array. The function signature is:
numpy.sort(a, axis, kind, order)# Parameter descriptions:# a: array to be sorted# axis: axis along which to sort the array; if the array is flat, it is flattened, sorting along the last axis# kind: defaults to 'quicksort'# order: if the array has fields, the field to sort by -
numpy.argsort()
numpy.argsort() returns the indices that would sort the array values in ascending order.
import numpy as np
x = np.array([3, 1, 2])print ('Our array:')print (x)print ('\\n')print ('Calling argsort() on x:')y = np.argsort(x)print (y)print ('\\n')print ('Reconstruct the original array in sorted order:')print (x[y])-
numpy.lexsort()
numpy.lexsort() sorts multiple sequences. Think of it as sorting a spreadsheet where each column represents a sequence, with sorting given priority to the later columns.
import numpy as np
nm = ('raju','anil','ravi','amar')dv = ('f.y.', 's.y.', 's.y.', 'f.y.')ind = np.lexsort((dv,nm))print ('Calling lexsort() function:')print (ind)print ('\\n')print ('Using this index to get the sorted data:')print ([nm[i] + ", " + dv[i] for i in ind])- msort、sort_complex、partition、argpartition
| Function | Description |
|---|---|
| msort(a) | Sorts the array along the first axis and returns a sorted copy. np.msort(a) is equivalent to np.sort(a, axis=0). |
| sort_complex(a) | Sorts complex numbers by real part first, then imaginary part. |
| partition(a, kth[, axis, kind, order]) | Partitions the array around a given index kth |
| argpartition(a, kth[, axis, kind, order]) | Partitions the array along the specified axis using the given kth index with optional algorithm |
-
numpy.argmax() and numpy.argmin()
numpy.argmax() and numpy.argmin() return the indices of the maximum and minimum elements along the given axis, respectively.
-
numpy.nonzero()
numpy.nonzero() returns the indices of the non-zero elements in the input array.
-
numpy.where()
numpy.where() returns the indices of elements in the input array that satisfy a given condition.
-
numpy.extract()
numpy.extract() extracts elements from an array that satisfy a condition and returns them.
NumPy Byte Swapping
On almost all machines, multi-byte objects are stored as a contiguous sequence of bytes. Endianness is the storage rule for multi-byte program objects.
- Big-endian: the high-order byte is stored at the low memory address, and the low-order byte at the high memory address; this storage pattern is somewhat like treating data as a string: addresses increase from low to high, and the data is placed from high to low; this matches our reading habit.
- Little-endian: the high-order byte is stored at the high memory address, and the low-order byte at the low memory address; this storage pattern effectively combines address order and data significance, with high-address parts having high weight and low-address parts having low weight.
numpy.ndarray.byteswap() swaps the byte order of every element in the ndarray.
import numpy as np
A = np.array([1, 256, 8755], dtype=np.int16)print(A)print(list(map(hex, A)))print(A.byteswap(inplace=True))print(list(map(hex, A)))Numpy Copies and Views
A copy is a complete duplicate of the data; if we modify the copy, it will not affect the original data, and the physical memory locations are different.
A view is an alias or reference to the data; through that alias, you can access and operate on the original data, but no data copy is made. If you modify the view, it will affect the original data, and the memory location is the same.
Views generally occur in:
- numpy slicing operations that return a view of the original data.
- calling ndarray’s view() function to produce a view.
A copy generally occurs in:
- Slicing a Python sequence and calling deepcopy().
- Calling ndarray.copy() to produce a copy.
import numpy as np
a = np.arange(6)print ('Our array:')print (a)print ('Calling id() function:')print (id(a))print ('a assigned to b:')b = aprint (b)print ('b has the same id():')print (id(b))print ('Modify b’s shape:')b.shape = 3,2print (b)print ('a shape also changed:')print (a)Views or Shallow Copy
ndarray.view() creates a new array object; the view’s shape changes do not affect the original data.
import numpy as np
# Initially a is a 3x2 arraya = np.arange(6).reshape(3,2)print ('Array a:')print (a)print ('Create a view of a:')b = a.view()print (b)print ('Different id() for a and b:')print ('a id():')print (id(a))print ('b id():')print (id(b))# Modifying b's shape does not modify ab.shape = 2,3print ('b shape:')print (b)print ('a shape:')print (a)
# Slicing to create views modifies data and affects the original array:arr = np.arange(12)print ('Our array:')print (arr)print ('Create slices:')a=arr[3:]b=arr[3:]a[1]=123b[2]=234print(arr)print(id(a),id(b),id(arr[3:]))Copies or Deep Copy
ndarray.copy() creates a copy. Modifications to the copy do not affect the original data; they do not share memory.
import numpy as np
a = np.array([[10,10], [2,3], [4,5]])print ('Array a:')print (a)print ('Create a deep copy of a:')b = a.copy()print ('Array b:')print (b)# b and a do not share any contentprint ('Can we write to b to write to a?')print (b is a)print ('Modify b:')b[0,0] = 100print ('Modified array b:')print (b)print ('a remains unchanged:')print (a)Numpy Matrix Library
NumPy includes a matrix library numpy.matlib; the functions in this module return a matrix rather than an ndarray.
A matrix is a rectangular array of elements arranged in rows and columns.
Matrix elements can be numbers, symbols, or mathematical expressions.
Transpose Matrix
NumPy not only supports the numpy.transpose function to swap the array’s axes, but also supports the T attribute.
For example, for a matrix with m rows and n columns, using the T attribute converts it to an n-by-m matrix.

import numpy as np
a = np.arange(12).reshape(3,4)
print ('Original array:')print (a)print ('\\n')
print ('Transposed array:')print (a.T)matlib.empty()
matlib.empty() function returns a new matrix, with the syntax:
numpy.matlib.empty(shape, dtype, order)
# Parameter explanations:# shape: integer or tuple of integers defining the new matrix shape# Dtype: optional, data type# order: C (row-major) or F (column-major)
import numpy.matlibimport numpy as np
print (np.matlib.empty((2,2)))# Fill with random datanumpy.matlib.zeros()
numpy.matlib.zeros() function creates a matrix filled with zeros.
import numpy as np
print (np.matlib.zeros((2,2)))numpy.matlib.ones()
numpy.matlib.ones() function creates a matrix filled with ones.
import numpy.matlibimport numpy as np
print (np.matlib.ones((2,2)))numpy.matlib.eye()
numpy.matlib.eye() function returns a matrix with 1s on the diagonal and zeros elsewhere.
numpy.matlib.eye(n, M,k, dtype)
# Parameter explanations:# n: number of rows to return# M: number of columns to return, default is n# k: index of the diagonal# dtype: data type
import numpy.matlibimport numpy as np
print (np.matlib.eye(n = 3, M = 4, k = 0, dtype = float))numpy.matlib.identity()
numpy.matlib.identity() function returns the identity matrix of a given size.
The identity matrix is a square matrix with 1s on the main diagonal from the top-left to the bottom-right, and 0s elsewhere.
import numpy.matlibimport numpy as np
# Size 5, type is floating pointprint (np.matlib.identity(5, dtype = float))numpy.matlib.rand()
numpy.matlib.rand() function creates a matrix of a given size with random data.
import numpy.matlibimport numpy as np
print (np.matlib.rand(3,3))
# Matrices are always two-dimensional, while ndarray is an n-dimensional array. Both objects are interchangeable.import numpy.matlibimport numpy as np
i = np.matrix('1,2;3,4')print (i)
j = np.asarray(i)print (j)
k = np.asmatrix (j)print (k)Numpy Linear Algebra
NumPy provides a linear algebra function library linalg, which includes all the functionality needed for linear algebra. See the description below:
| Function | Description | Function |
|---|---|---|
| dot | The dot product of two arrays, i.e., element-wise multiplication. | numpy.dot(a, b, out=None) |
| vdot | The dot product of two vectors. If the first argument is complex, its conjugate is used. If the argument is multi-dimensional, it will be flattened | numpy.vdot(a, b) |
| inner | Returns the vector inner product of 1-D arrays. For higher dimensions, it returns the sum of the products over the last axis | numpy.vdot(a, b) |
| matmul | The matrix product of two arrays | numpy.inner(a, b) |
| determinant | The determinant of an array | numpy.det(a, b) |
| solve | Solve a linear matrix equation | numpy.solve(a, b) |
| inv | Calculate the inverse of a matrix | numpy.inv(a) |
-
matmul
numpy.matmul function returns the matrix product of two arrays. While it returns the normal product for 2-D arrays, if either argument has dimension greater than 2, it is treated as a stack of matrices residing in the last two indices and broadcast accordingly.
On the other hand, if either argument is a 1-D array, it is promoted to a matrix by prepending a 1 to its shape and is removed after the multiplication.
For 2-D arrays, it is the matrix product:
import numpy.matlibimport numpy as npa = [[1,0],[0,1]]b = [[4,1],[2,2]]print (np.matmul(a,b))# 2-D and 1-D operationsa = [[1,0],[0,1]]b = [1,2]print (np.matmul(a,b))print (np.matmul(b,a))# Arrays with dimension greater than 2a = np.arange(8).reshape(2,2,2)b = np.arange(4).reshape(2,2)print (np.matmul(a,b))
NumPy IO
NumPy can read and write text data or binary data on disk.
NumPy introduces a simple file format for ndarray objects: npy.
.npy files are used to store the data, shape, dtype and other information needed to reconstruct the ndarray.
Common IO functions include:
- load() and save() are the two main functions for reading and writing array data; by default, arrays are stored in an uncompressed raw binary format in files with the .npy extension.
- savez() is used to write multiple arrays to a file; by default, arrays are stored in an uncompressed raw binary format in files with the .npz extension.
- loadtxt() and savetxt() handle ordinary text files (.txt, etc.)
-
numpy.save()
numpy.save() function saves an array to a file with a .npy extension.
numpy.save(file, arr, allow_pickle=True, fix_imports=True) -
np.savez
numpy.savez() function saves multiple arrays to a file with a .npz extension.
numpy.savez(file, *args, **kwds) -
savetxt()
savetxt() function stores data in a simple text file format; to retrieve the data, use loadtxt().
np.loadtxt(FILENAME, dtype=int, delimiter=' ')np.savetxt(FILENAME, a, fmt="%d", delimiter=",")The delimiter parameter can specify various delimiters, per-column converters, the number of lines to skip, and so on.
Numpy + Matplotlib
Matplotlib is Python’s plotting library. It can be used with NumPy, providing an effective open-source MATLAB-like alternative. It can also be used with GUI toolkits like PyQt and wxPython.
pip3 installation:
pip3 install matplotlib
# Installation verificationpip3 list | grep matplotlibUsage:
import numpy as npfrom matplotlib import pyplot as plt
x = np.arange(1,11)y = 2 * x + 5plt.title("Matplotlib demo")plt.xlabel("x axis caption")plt.ylabel("y axis caption")plt.plot(x,y)plt.show()Using Chinese
Matplotlib does not support Chinese by default, and we can resolve this with the following simple method.
- Download Source Han Sans
- Put the downloaded OTF font into the code directory
matplotlib.font_manager.FontProperties(fname="SourceHanSansSC-Bold.otf")fname specifies the font path
import numpy as npfrom matplotlib import pyplot as pltimport matplotlib
# fname is the path to your downloaded font library; note SourceHanSansSC-Bold.otf pathzhfont1 = matplotlib.font_manager.FontProperties(fname="SourceHanSansSC-Bold.otf")
x = np.arange(1,11)y = 2 * x + 5plt.title("菜鸟教程 - 测试", fontproperties=zhfont1)
# fontproperties sets Chinese display, fontsize sets font sizeplt.xlabel("x 轴", fontproperties=zhfont1)plt.ylabel("y 轴", fontproperties=zhfont1)plt.plot(x,y)plt.show()
numpy計算
numpyビット演算
ビット演算は、二進数の各ビットレベルで操作を行う演算の一種で、数値全体の値を考慮せず、二進数の各ビットを直接操作します。
ビット演算は、計算機科学において低レベルデータの最適化や処理に広く用いられます。
NumPy の “bitwise_” で始まる関数はビット演算関数です。
NumPy のビット演算には以下の関数が含まれます:
| 関数 | 説明 | 演算子 |
|---|---|---|
| bitwise_and | ビットAND、配列要素に対してビットANDを実行します | & |
| bitwise_or | ビットOR、配列要素に対してビットORを実行します | |
| bitwise_xor | ビットXOR、 | ^ |
| bitwise_not | ビット反転 | ~ |
| invert | ビット反転 | ~ |
| left_shift | 左シフト演算、2進数表現のビットを左へ移動 | << |
| right_shift | 右シフト演算、2進数表現のビットを右へ移動 | >> |
import numpy as np
arr1 = np.array([True, False, True], dtype=bool)arr2 = np.array([False, True, False], dtype=bool)
result_and = np.bitwise_and(arr1, arr2)result_or = np.bitwise_or(arr1, arr2)result_xor = np.bitwise_xor(arr1, arr2)result_not = np.bitwise_not(arr1)
print("AND:", result_and) # [False, False, False]print("OR:", result_or) # [True, True, True]print("XOR:", result_xor) # [True, True, True]print("NOT:", result_not) # [False, True, False]
# 按位取反arr_invert = np.invert(np.array([1, 2], dtype=np.int8))print("Invert:", arr_invert) # [-2, -3]
# 左移位运算arr_left_shift = np.left_shift(5, 2)print("Left Shift:", arr_left_shift) # 20
# 右移位运算arr_right_shift = np.right_shift(10, 1)print("Right Shift:", arr_right_shift) # 5字符串函数
以下函数用于对 dtype 为 numpy.string_或 numpy.unicode_ 的数组执行向量化字符串操作。 它们基于 Python 内置库中的标准字符串函数。
これらの関数は文字列配列クラス(numpy.char)に定義されています。
| 函数 | 説明 |
|---|---|
| add() | 二つの配列の各要素の文字列を結合します |
| multiply() | 要素ごとに連結された文字列を返します |
| center() | 文字列を中央寄せにし、左側と右側を指定した文字で埋めます。 |
| capitalize() | 文字列の最初の文字を大文字に変換します |
| title() | 文字列の各単語の最初の文字を大文字にします |
| lower() | 配列要素を小文字に変換します |
| upper() | 配列要素を大文字に変換します |
| split() | 指定した区切り文字で文字列を分割し、配列リストを返します |
| splitlines() | 要素内の行リストを返し、改行文字で分割 |
| strip() | 要素の先頭または末尾の特定の文字を削除します |
| join() | 指定した区切り文字で配列要素を結合します |
| replace() | 文字列中のすべてのサブ文字列を新しい文字列に置換します |
| decode() | 配列要素ごとに str.decode を呼び出します |
| encode() | 配列要素ごとに str.encode を呼び出します |
- numpy.char.add()/multiply()/center()
numpy.char.add() 関数は、二つの配列の要素を順に文字列結合します。
import numpy as np
print ('文字列を結合します:')print (np.char.add(['hello'],[' xyz']))print ('\\n')
print ('結合の例:')print (np.char.add(['hello', 'hi'],[' abc', ' xyz']))
print (np.char.multiply('Runoob ',3))
# np.char.center(str , width,fillchar) :# str: 文字列,width: 幅,fillchar: 埋める文字print (np.char.center('Runoob', 20,fillchar = '*'))- numpy.char.capitalize()/title()/lower()/upper()
import numpy as np
print (np.char.capitalize('runoob'))
print (np.char.capitalize('runoob'))
#操作数组print (np.char.lower(['RUNOOB','GOOGLE']))
# 操作字符串print (np.char.lower('RUNOOB'))- numpy.char.split()/splitlines()/strip()
numpy.char.split() 通过指定分隔符对字符串进行分割,并返回数组。默认情况下,分隔符为空格。
import numpy as np
# 分隔符默认为空格print (np.char.split ('i like runoob?'))# 分隔符为 .print (np.char.split ('www.runoob.com', sep = '.'))
# 换行符 \\n# \\n,\\r,\\r\\n 都可用作换行符。print (np.char.splitlines('i\\nlike runoob?'))print (np.char.splitlines('i\\rlike runoob?'))
# 移除字符串头尾的 a 字符print (np.char.strip('ashok arunooba','a'))
# 移除数组元素头尾的 a 字符print (np.char.strip(['arunooba','admin','java'],'a'))- numpy.char.join()/replace()/encode()/decode()
numpy.char.join() 関数は、指定した区切り文字を用いて配列内の要素や文字列を結合します
import numpy as np
# 操作字符串print (np.char.join(':','runoob'))
# 指定多个分隔符操作数组元素print (np.char.join([':','-'],['runoob','google']))
print (np.char.replace ('i like runoob', 'oo', 'cc'))
a = np.char.encode('runoob', 'cp500')print (a)
print (np.char.decode(a,'cp500'))numpy数学函数
三角函数
NumPy は標準的な三角関数 sin()、cos()、tan() を提供します。
import numpy as np
a = np.array([0,30,45,60,90])print ('異なる角度の正弦値:')# 角度をラジアンへ変換するには pi/180 を掛けるprint (np.sin(a*np.pi/180))print ('\\n')print ('配列中の角度の余弦値:')print (np.cos(a*np.pi/180))print ('\\n')print ('配列中の角度の正接値:')print (np.tan(a*np.pi/180))arcsin、arccos、和 arctan 関数は、与えられた角度の sin、cos、tan の逆関数を返します。
这些函数的结果可以通过 numpy.degrees() 函数将弧度转换为角度。
import numpy as np
a = np.array([0,30,45,60,90])print ('含有正弦值的数组:')sin = np.sin(a*np.pi/180)print (sin)print ('\\n')print ('计算角度的反正弦,返回值以弧度为单位:')inv = np.arcsin(sin)print (inv)print ('\\n')print ('通过转化为角度制来检查结果:')print (np.degrees(inv))print ('\\n')print ('arccos 和 arctan 函数行为类似:')cos = np.cos(a*np.pi/180)print (cos)print ('\\n')print ('反余弦:')inv = np.arccos(cos)print (inv)print ('\\n')print ('角度制单位:')print (np.degrees(inv))print ('\\n')print ('tan 函数:')tan = np.tan(a*np.pi/180)print (tan)print ('\\n')print ('反正切:')inv = np.arctan(tan)print (inv)print ('\\n')print ('角度制单位:')print (np.degrees(inv))舍入函数
-
numpy.around() 関数は、指定された数値の四捨五入値を返します。
# numpy.around(a,decimals)# a: 配列# decimals: 四捨五入する小数点以下の桁数。 デフォルトは0。 もし負なら、小数点の左側の位置まで四捨五入されますimport numpy as npa = np.array([1.0,5.55, 123, 0.567, 25.532])print ('原数组:')print (a)print ('\\n')print ('舍入后:')print (np.around(a))print (np.around(a, decimals = 1))print (np.around(a, decimals = -1)) -
numpy.floor() 指定した式以下の最大の整数を返します、すなわち切り捨て。
import numpy as npa = np.array([-1.7, 1.5, -0.2, 0.6, 10])print ('提供的数组:')print (a)print ('\\n')print ('修改后的数组:')print (np.floor(a)) -
numpy.ceil() 指定した式以上の最小の整数を返します、すなわち切り上げ。
import numpy as npa = np.array([-1.7, 1.5, -0.2, 0.6, 10])print ('提供的数组:')print (a)print ('\\n')print ('修改后的数组:')print (np.ceil(a))
算术函数
NumPy の算術関数には、単純な加算・減算・乗算・除算が含まれます: add()、subtract()、multiply()、divide()。
配列は同じ形状であるか、配列ブロードキャスト規則に従う必要があります。
import numpy as np
a = np.arange(9, dtype = np.float_).reshape(3,3)print ('第一个数组:')print (a)print ('\\n')print ('第二个数组:')b = np.array([10,10,10])print (b)print ('\\n')print ('两个数组相加:')print (np.add(a,b))print ('\\n')print ('两个数组相减:')print (np.subtract(a,b))print ('\\n')print ('两个数组相乘:')print (np.multiply(a,b))print ('\\n')print ('两个数组相除:')print (np.divide(a,b))-
numpy.reciprocal()
numpy.reciprocal() 関数は、引数の要素ごとの逆数を返します。例えば 1/4 の逆数は 4/1 です。
import numpy as npa = np.array([0.25, 1.33, 1, 100])print ('我们的数组是:')print (a)print ('\\n')print ('调用 reciprocal 函数:')print (np.reciprocal(a)) -
numpy.power()
numpy.power() 関数は、最初の入力配列の要素を底として、対応する第二の入力配列の要素の冪を計算します。
import numpy as npa = np.array([10,100,1000])print ('我们的数组是;')print (a)print ('\\n')print ('调用 power 函数:')print (np.power(a,2))print ('\\n')print ('第二个数组:')b = np.array([1,2,3])print (b)print ('\\n')print ('再次调用 power 函数:')print (np.power(a,b)) -
numpy.mod()
numpy.mod() は、入力配列の要素ごとの余りを計算します。 numpy.remainder() も同じ結果を生みます。
import numpy as np
a = np.array([10,20,30])b = np.array([3,5,7])print ('第一个数组:')print (a)print ('\\n')print ('第二个数组:')print (b)print ('\\n')print ('调用 mod() 函数:')print (np.mod(a,b))print ('\\n')print ('调用 remainder() 函数:')print (np.remainder(a,b))統計関数
-
numpy.amin() と numpy.amax()
numpy.amin() は、配列の要素を指定された軸に沿って最小値を計算します。
numpy.amin(a, axis=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)# パラメータの説明:# a: 入力の配列。NumPy の配列または同様の配列オブジェクト。# axis: オプション。どの軸に沿って最小値を計算するかを指定。指定しない場合は配列全体の最小値を返す。整数で軸のインデックスを表すことも、複数の軸を表すタプルも可能。# out: オプション。結果の格納先。# keepdims: オプション。True の場合、結果配列の次元を入力配列と同じに保つ。False(デフォルト)の場合、計算後の次元が1の軸は削除される。# initial: オプション。配列の要素上で最小値を計算する際の初期値を指定。# where: オプション。ブール配列で、条件を満たす要素のみを考慮。numpy.amax() は、配列の要素を指定された軸に沿って最大値を計算します。
numpy.amax(a, axis=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)# パラメータの説明:# a: 入力の配列。NumPy の配列または同様の配列オブジェクト。# axis: オプション。どの軸に沿って最大値を計算するかを指定。指定しない場合は配列全体の最大値を返す。整数で軸のインデックスを表すことも、複数の軸を表すタプルも可能。# out: オプション。結果の格納先。# keepdims: オプション。True の場合、結果配列の次元を入力配列と同じに保つ。False(デフォルト)の場合、計算後の次元が1の軸は削除される。# initial: オプション。配列の要素上で最大値を計算する際の初期値を指定。# where: オプション。ブール配列で、条件を満たす要素のみを考慮。
import numpy as np
a = np.array([[3,7,5],[8,4,3],[2,4,9]])print ('我们的数组是:')print (a)print ('\\n')print ('调用 amin() 函数:')print (np.amin(a,1))print ('\\n')print ('再次调用 amin() 函数:')print (np.amin(a,0))print ('\\n')print ('调用 amax() 函数:')print (np.amax(a))print ('\\n')print ('再次调用 amax() 函数:')print (np.amax(a, axis = 0))-
numpy.ptp()
numpy.ptp() 関数は、配列中の要素の最大値と最小値の差(最大値 - 最小値)を計算します。
numpy.ptp(a,axis=None,out=None,keepdims=<no value>,initial=<no value>,where=<no value>)# パラメータの説明:# a: 入力の配列。NumPy の配列または同様の配列オブジェクト。# axis: オプション。峰-峰値を計算する軸を指定。指定しない場合は配列全体の峰-峰値を返す。整数で軸のインデックスを表すことも、複数の軸を表すタプルも可能。# out: オプション。結果の格納先。# keepdims: オプション。True の場合、結果配列の次元を入力配列と同じに保つ。False(デフォルト)の場合、計算後の次元が1の軸は削除される。# initial: オプション。配列の要素上で峰-峰値を計算する際の初期値を指定。# where: オプション。ブール配列で、条件を満たす要素のみを考慮。import numpy as npa = np.array([[3,7,5],[8,4,3],[2,4,9]])print ('我们的数组是:')print (a)print ('\\n')print ('调用 ptp() 函数:')print (np.ptp(a))print ('\\n')print ('沿轴 1 调用 ptp() 函数:')print (np.ptp(a, axis = 1))print ('\\n')print ('沿轴 0 调用 ptp() 函数:')print (np.ptp(a, axis = 0)) -
numpy.percentile()
百分位数は統計で用いられる尺度で、ある値以下の観測値の割合を表します。関数 numpy.percentile() は以下のパラメータを受け取ります。
まず百分位数を明確にする: 第 p 百分位数は、少なくとも p% のデータ項がこの値以下であり、かつ少なくとも (100-p)% のデータ項がこの値以上となるような値です。
例として、入学試験の成績はしばしば百分位数で報告されます。例えば、ある受験者の国語の原点が 54 点だった場合、同じ試験を受けた他の学生と比較して彼の成績がどうかは分かりにくいですが、もし原点 54 点がちょうど第 70 百分位数に対応する場合、約 70% の学生の得点が彼より低く、約 30% の学生の得点が彼より高いことが分かります。
ここで p = 70。numpy.percentile(a, q, axis)# パラメータの説明:# a: 入力配列# q: 計算する百分位数、0 ~ 100 の間# axis: 百分位数を計算する軸import numpy as npa = np.array([[10, 7, 4], [3, 2, 1]])print ('我们的数组是:')print (a)print ('调用 percentile() 函数:')# 50% の分位数は、a の並べ替え後の中位数print (np.percentile(a, 50))# axis を 0 にすると縦列で求めるprint (np.percentile(a, 50, axis=0))# axis を 1 にすると横行で求めるprint (np.percentile(a, 50, axis=1))# 维度を保つprint (np.percentile(a, 50, axis=1, keepdims=True)) -
numpy.median()
numpy.median() 関数は、配列 a の要素の中央値(中位数)を計算します。
numpy.median(a, axis=None, out=None, overwrite_input=False, keepdims=<no value>)# パラメータの説明:# a: 入力の配列。NumPy の配列または同様の配列オブジェクト。# axis: オプション。どの軸に沿って中位数を計算するかを指定。指定しない場合は配列全体の中位数を計算。整数で軸のインデックスを表すことも、複数の軸を表すタプルも可能。# out: オプション。結果の格納先。# overwrite_input: オプション。True の場合、入力配列のメモリを計算に利用することを許可。場合によってパフォーマンスが向上するが、入力配列の内容を変更する可能性。# keepdims: オプション。True の場合、結果配列の次元を入力配列と同じに保つ。False(デフォルト)の場合、計算後の次元が1の軸は削除される。import numpy as npa = np.array([[30,65,70],[80,95,10],[50,90,60]])print ('我们的数组是:')print (a)print ('\\n')print ('调用 median() 函数:')print (np.median(a))print ('\\n')print ('沿轴 0 调用 median() 函数:')print (np.median(a, axis = 0))print ('\\n')print ('沿轴 1 调用 median() 函数:')print (np.median(a, axis = 1)) -
numpy.mean()
numpy.mean() 関数は、軸が指定されていれば、配列の要素の算術平均を返します。
算術平均値は、軸の要素の合計を要素の数で割った値です。
numpy.mean(a, axis=None, dtype=None, out=None, keepdims=<no value>)# パラメータの説明:# a: 入力の配列。NumPy の配列または同様の配列オブジェクト。# axis: オプション。どの軸に沿って平均値を計算するかを指定。指定しない場合は配列全体の平均値を計算。整数で軸のインデックスを表すことも、複数の軸を表すタプルも可能。# dtype: オプション。出力のデータ型を指定。指定しない場合は入力データの型に基づく。# out: オプション。結果の格納先。# keepdims: オプション。True の場合、結果配列の次元を入力配列と同じに保つ。False(デフォルト)の場合、計算後の次元が1の軸は削除される。 -
numpy.average()
numpy.average() は、別の配列で与えられた各自の重みを用いて、配列中の要素の加重平均を計算します。
この関数は軸引数を受け付けます。 未指定の場合、配列は展開されます。
加重平均値は、各数値に対応する重みを掛けて合計し、総和を全体の重みの合計で割った値です。
numpy.average(a, axis=None, weights=None, returned=False)# パラメータの説明:# a: 入力の配列。NumPy の配列または同様の配列オブジェクト。# axis: オプション。どの軸に沿って加重平均を計算するかを指定。指定しない場合は配列全体の加重平均を計算。整数で軸のインデックスを表すことも、複数の軸を表すタプルも可能。# weights: オプション。データ点の重みを指定。重み配列を提供しない場合は等重み。# returned: オプション。True の場合、加重平均と重みの和を同時に返します。 -
numpy.average()
numpy.average() は、別の配列で与えられた各自の重みを用いて、配列中の要素の加重平均を計算します。
この関数は軸引数を受け付けます。 未指定の場合、配列は展開されます。
加重平均値は、各数値に対応する重みを掛けて合計し、総和を全体の重みの合計で割った値です。
numpy.average(a, axis=None, weights=None, returned=False)# パラメータの説明:# a: 入力の配列。NumPy の配列または同様の配列オブジェクト。# axis: オプション。どの軸に沿って加重平均を計算するかを指定。指定しない場合は配列全体の加重平均を計算。整数で軸のインデックスを表すことも、複数の軸を表すタプルも可能。# weights: オプション。データ点の重みを指定。重み配列を提供しない場合は等重み。# returned: オプション。True の場合、加重平均と重みの和を同時に返します。import numpy as npa = np.array([1,2,3,4])print ('我们的数组是:')print (a)print ('\\n')print ('调用 average() 函数:')print (np.average(a))print ('\\n')# 不指定权重时相当于 mean 函数wts = np.array([4,3,2,1])print ('再次调用 average() 函数:')print (np.average(a,weights = wts))print ('\\n')# 如果 returned 参数设为 true,则返回权重的和print ('权重的和:')print (np.average([1,2,3, 4],weights = [4,3,2,1], returned = True))# 在多维数组中,可以指定用于计算的轴。a = np.arange(6).reshape(3,2)print ('我们的数组是:')print (a)print ('\\n')print ('修改后的数组:')wt = np.array([3,5])print (np.average(a, axis = 1, weights = wt))print ('\\n')print ('修改后的数组:')print (np.average(a, axis = 1, weights = wt, returned = True)) -
標準偏差
標準偏差はデータの平均値の分散の程度を表す尺度です。
標準偏差は分散の算術平方根です。
標準偏差の公式は如下:
std = sqrt(mean((x - x.mean())^2))import numpy as npprint (np.std([1,2,3,4])) -
方差
統計における分散(標本分散)は、各サンプル値と全体サンプル値の平均値との差の平方の平均、すなわち mean((x - x.mean())** 2)。
言い換えれば、標準偏差は分散の平方根です。
import numpy as npprint (np.var([1,2,3,4]))
NumPy 排序、条件筛选函数
NumPy は複数のソート方法を提供します。 これらのソート関数は、異なるソートアルゴリズムを実装しており、アルゴリズムごとの特長は実行速度、最悪ケースの性能、必要な作業スペース、アルゴリズムの安定性です。 下表は三つのソートアルゴリズムの比較を示します。
| 種類 | 速度 | 最悪ケース | 作業スペース | 安定性 |
|---|---|---|---|---|
| ’quicksort’(クイックソート) | 1 | O(n^2) | O(1) | 否 |
| ’mergesort’(マージソート) | 2 | O(n * log(n)) | O(n) | はい |
| ’heapsort’(ヒープソート) | 3 | O(n*log(n)) | O(1) | 否 |
-
numpy.sort()
numpy.sort() 関数は、入力配列のソート済みコピーを返します。関数形式は以下のとおりです:
numpy.sort(a, axis, kind, order)# パラメータの説明:# a: ソートする配列# axis: その軸に沿って配列をソートします。配列が展開されると、最後の軸に沿ってソートされます。axis=0 は列方向、axis=1 は行方向にソートします# kind: デフォルトは'quicksort'(クイックソート)# order: 配列がフィールドを含む場合には、ソートするフィールド -
numpy.argsort()
numpy.argsort() 関数は、配列の値を小さい順に並べたときのインデックス値を返します。
import numpy as npx = np.array([3, 1, 2])print ('我们的数组是:')print (x)print ('\\n')print ('对 x 调用 argsort() 函数:')y = np.argsort(x)print (y)print ('\\n')print ('以排序后的顺序重构原数组:')print (x[y]) -
numpy.lexsort()
numpy.lexsort() は、複数のシーケンスをソートするために使用します。スプレッドシートの各列が1つのシーケンスで、ソート時には後ろの列を優先して並べ替えると考えてください。
import numpy as npnm = ('raju','anil','ravi','amar')dv = ('f.y.', 's.y.', 's.y.', 'f.y.')ind = np.lexsort((dv,nm))print ('调用 lexsort() 函数:')print (ind)print ('\\n')print ('使用这个索引来获取排序后的数据:')print ([nm[i] + ", " + dv[i] for i in ind]) -
msort、sort_complex、partition、argpartition
函数 描述 msort(a) 配列を第一軸でソートし、ソート済みの配列のコピーを返します。np.msort(a) は np.sort(a, axis=0) と同じです。 sort_complex(a) 複素数を、実部、虚部の順にソートします。 partition(a, kth[, axis, kind, order]) 指定した数を基準に、配列を分割します argpartition(a, kth[, axis, kind, order]) keyword kind を使って、指定した軸に沿って配列を分割します -
numpy.argmax() と numpy.argmin()
numpy.argmax() および numpy.argmin() 関数は、それぞれ、指定した軸に沿って最大値と最小値のインデックスを返します。
-
numpy.nonzero()
numpy.nonzero() 関数は、入力配列の非ゼロ要素のインデックスを返します。
-
numpy.where()
numpy.where() 関数は、入力配列の条件を満たす要素のインデックスを返します。
-
numpy.extract()
numpy.extract() 関数は、ある条件に基づいて配列から要素を抽出し、条件を満たす要素を返します。
NumPy バイトスワップ
ほぼすべての機械では、多バイトのオブジェクトは連続したバイト順で格納されます。バイト順は、多バイトのデータを格納するための規則です。
- ビッグエンディアン:データの高位バイトがメモリの低アドレスに格納され、低位バイトがメモリの高アドレスに格納されます。この格納モードは、データを文字列として扱うようにアドレスが小さい方から大きい方へ増え、データが高位から低位へ配置されることに似ています。私たちの読み方と一致します。
- リトルエンディアン:データの高位バイトがメモリの高アドレスに格納され、低位バイトがメモリの低アドレスに格納されます。この格納モードはアドレスの高低とデータビットの重みを効果的に結びつけ、高アドレス部分の重みが大きく、低アドレス部分の重みが小さいです。
numpy.ndarray.byteswap() は ndarray の各要素のバイト順を大小のエンディアンに変換します。
import numpy as np
A = np.array([1, 256, 8755], dtype=np.int16)print(A)print(list(map(hex, A)))print(A.byteswap(inplace=True))print(list(map(hex, A)))Numpy 副本とビュー
コピーはデータの完全なコピーであり、コピーを変更しても元のデータには影響しません。物理メモリは同じ場所にはありません。
ビューはデータの別名または参照であり、同じデータへアクセス・操作しますが、元のデータはコピーされません。ビューを変更すると、元のデータに影響します。物理メモリは同じ場所にあります。
ビューは通常次の場合に発生します:
- numpy のスライス操作が元データのビューを返す場合。
- ndarray の view() 関数を呼び出してビューを作成する場合。
コピーは通常次の場合に発生します:
- Python のシーケンスのスライス操作、deepCopy() 関数を呼び出す場合。
- ndarray の copy() 関数を呼び出してコピーを作成する場合。
無コピー
簡単な代入は配列オブジェクトのコピーを作成しません。 代わりに、元の配列と同じ id() を使用して参照します。 id() は Python オブジェクトの一般的な識別子を返し、C のポインタに似ています。
さらに、配列のいかなる変更も別の配列に反映されます。 例えば、ある配列の形状を変更すると、別の配列の形状も変更されます。
import numpy as np
a = np.arange(6)print ('我们的数组是:')print (a)print ('调用 id() 函数:')print (id(a))print ('a 赋值给 b:')b = aprint (b)print ('b 拥有相同 id():')print (id(b))print ('修改 b 的形状:')b.shape = 3,2print (b)print ('a 的形状也修改了:')print (a)视图或浅拷贝
ndarray.view() 方会创建一个新的数组对象,该方法创建的新数组的维数变化不会改变原始数据的维数。
import numpy as np
# 最开始 a 是个 3X2 的数组a = np.arange(6).reshape(3,2)print ('数组 a:')print (a)print ('创建 a 的视图:')b = a.view()print (b)print ('两个数组的 id() 不同:')print ('a 的 id():')print (id(a))print ('b 的 id():' )print (id(b))# 修改 b 的形状,并不会修改 ab.shape = 2,3print ('b 的形状:')print (b)print ('a 的形状:')print (a)
# 使用切片创建视图修改数据会影响到原始数组:arr = np.arange(12)print ('我们的数组:')print (arr)print ('创建切片:')a=arr[3:]b=arr[3:]a[1]=123b[2]=234print(arr)print(id(a),id(b),id(arr[3:]))副本或深拷贝
ndarray.copy() 函数创建一个副本。 对副本数据进行修改,不会影响到原始数据,它们物理内存不在同一位置。
import numpy as np
a = np.array([[10,10], [2,3], [4,5]])print ('数组 a:')print (a)print ('创建 a 的深层副本:')b = a.copy()print ('数组 b:')print (b)# b 与 a 不共享任何内容print ('我们能够写入 b 来写入 a 吗?')print (b is a)print ('修改 b 的内容:')b[0,0] = 100print ('修改后的数组 b:')print (b)print ('a 保持不变:')print (a)Numpy矩阵库
NumPy 中包含了一个矩阵ライブラリ numpy.matlib,该モジュール中の関数は矩阵を返し、ndarray オブジェクトは返しません。
一つの矩阵は、行(row)と列(column)からなる要素が並んだ矩形の配列です。
矩阵の要素は数字、記号、または数式として表現できます。
転置行列
NumPy では numpy.transpose 関数で配列の次元を変更することもできますが、T 属性を使用することもできます。
例えば m 行 n 列の行列がある場合、T 属性を使うと n 行 m 列の行列に変換できます。

import numpy as np
a = np.arange(12).reshape(3,4)
print ('原数组:')print (a)print ('\\n')
print ('转置数组:')print (a.T)matlib.empty()
matlib.empty() 関数は、新しいマトリクスを返します。文法形式は:
numpy.matlib.empty(shape, dtype, order)
# パラメータの説明:# shape: 新しいマトリクスの形状を定義する整数または整数のタプル# Dtype: オプション、データ型# order: C(行優先) または F(列優先)
import numpy.matlibimport numpy as np
print (np.matlib.empty((2,2)))# ランダムデータで埋めるnumpy.matlib.zeros()
numpy.matlib.zeros() 関数は、0 で埋められたマトリクスを作成します。
import numpy as np
print (np.matlib.zeros((2,2)))numpy.matlib.ones()
numpy.matlib.ones()関数は、1 で埋められたマトリクスを作成します。
import numpy.matlibimport numpy as np
print (np.matlib.ones((2,2)))numpy.matlib.eye()
numpy.matlib.eye() 関数は、対角線上の要素が 1、その他が 0 の行列を返します。
numpy.matlib.eye(n, M,k, dtype)
# パラメータの説明:# n: 返される行数# M: 返される列数、デフォルトは n# k: 対角線のインデックス# dtype: データ型
import numpy.matlibimport numpy as np
print (np.matlib.eye(n = 3, M = 4, k = 0, dtype = float))numpy.matlib.identity()
numpy.matlib.identity() 関数は、指定したサイズの単位行列を返します。
単位行列は正方行列で、左上から右下の対角線(主対角線)上の要素がすべて 1、その他は 0 です。
import numpy.matlibimport numpy as np
# サイズ5、型は浮動小数点print (np.matlib.identity(5, dtype = float))numpy.matlib.rand()
numpy.matlib.rand() 関数は、指定した大きさのマトリクスを生成し、データをランダムに埋めます。
import numpy.matlibimport numpy as np
print (np.matlib.rand(3,3))
# マトリクスは常に二次元ですが、ndarray は n 次元配列です。両方は互換性があります。import numpy.matlibimport numpy as np
i = np.matrix('1,2;3,4')print (i)
j = np.asarray(i)print (j)
k = np.asmatrix (j)print (k)Numpy線形代数
NumPy は線形代数関数ライブラリ linalg を提供しており、線形代数に必要な全機能を含んでいます。以下の説明を参照してください:
| 関数 | 説明 | 関数 |
|---|---|---|
| dot | 2つの配列の点積、要素ごとに乗算。 | numpy.dot(a, b, out=None) |
| vdot | 2つのベクトルの点積。最初の引数が複数の場合、それを展開して計算。 | numpy.vdot(a, b) |
| inner | 一次元配列のベクトル内積。より高次元の場合、最後の軸の和の積を返します | numpy.inner(a, b) |
| matmul | 2つの配列の行列積 | numpy.matmul(a, b) |
| determinant | 配列の行列式 | numpy.linalg.det(a) |
| solve | 線形方程式系を解く | numpy.linalg.solve(a, b) |
| inv | 行列の逆行列 | numpy.linalg.inv(a) |
-
matmul
numpy.matmul 関数は、2つの配列の行列積を返します。2次元配列の通常の積を返しますが、いずれかの引数の次元が2を超える場合、それを最後の2つのインデックスにある行列のスタックとして扱い、適切にブロードキャストします。
一方、いずれかの引数が1次元配列の場合、次元に 1 を付加して行列として昇格させ、乗算後に元に戻します。
2次元配列に対しては、それは行列積です:
import numpy.matlibimport numpy as np
a = [[1,0],[0,1]]b = [[4,1],[2,2]]print (np.matmul(a,b))
# 二次元と一次元の演算a = [[1,0],[0,1]]b = [1,2]print (np.matmul(a,b))print (np.matmul(b,a))
# 次元が二を超える配列a = np.arange(8).reshape(2,2,2)b = np.arange(4).reshape(2,2)print (np.matmul(a,b))Numpy IO
NumPy はディスク上のテキストデータやバイナリデータの読み書きができます。
NumPy は ndarray オブジェクト用のシンプルなファイル形式 npy を導入しています。
npy ファイルは、再構築する ndarray に必要なデータ、形状、dtype およびその他の情報を格納します。
よく使う IO 関数は以下のとおりです:
- load() および save() 関数は配列データの読み書きの2つの主要関数で、デフォルトでは、配列は未圧縮の原始的な二進形式で .npy 拡張子のファイルに保存されます。
- savez() 関数は複数の配列をファイルに書き込みます。デフォルトでは、配列は未圧縮の原始的な二進形式で .npz 拡張子のファイルに保存されます。
- loadtxt() および savetxt() 関数は通常のテキストファイル (.txt 等) を処理します
-
numpy.save()
numpy.save() 関数は配列を .npy 拡張子のファイルに保存します。
numpy.save(file, arr, allow_pickle=True, fix_imports=True) -
np.savez
numpy.savez() 関数は複数の配列を .npz 拡張子のファイルに保存します。
numpy.savez(file, *args, **kwds) -
savetxt()
savetxt() 関数はシンプルなテキストファイル形式でデータを保存します。対応する取得には loadtxt() 関数を使用します。
np.loadtxt(FILENAME, dtype=int, delimiter=' ')np.savetxt(FILENAME, a, fmt="%d", delimiter=",")delimiter パラメータは、さまざまな区切文字、特定の列の変換器関数、スキップする行数などを指定できます。
Numpy + Matplotlib
Matplotlib は Python の描画ライブラリです。 NumPy と併用することで、MatLab のオープンソース代替として効率的です。また、PyQt や wxPython などのグラフィックツールキットと一緒に使用することもできます。
pip3 のインストール:
pip3 install matplotlib
# インストールの検証pip3 list | grep matplotlib使用例:
import numpy as npfrom matplotlib import pyplot as plt
x = np.arange(1,11)y = 2 * x + 5plt.title("Matplotlib demo")plt.xlabel("x axis caption")plt.ylabel("y axis caption")plt.plot(x,y)plt.show()中国語の表示
Matplotlib はデフォルトでは中国語をサポートしていません。以下の簡単な方法で解決できます。
- 思源黑体をダウンロードします
- ダウンロードしたOTFフォントをコードファイルの下に置きます
matplotlib.font_manager.FontProperties(fname="SourceHanSansSC-Bold.otf")の fname にフォントライブラリのパスを指定します
import numpy as npfrom matplotlib import pyplot as pltimport matplotlib
# fname は あなたがダウンロードしたフォントライブラリのパス、SourceHanSansSC-Bold.otf のパスに注意zhfont1 = matplotlib.font_manager.FontProperties(fname="SourceHanSansSC-Bold.otf")
x = np.arange(1,11)y = 2 * x + 5plt.title("菜鸟教程 - 测试", fontproperties=zhfont1)
# fontproperties は中国語表示を設定し、fontsize はフォントサイズを設定plt.xlabel("x 轴", fontproperties=zhfont1)plt.ylabel("y 轴", fontproperties=zhfont1)plt.plot(x,y)plt.show()部分信息可能已经过时









