亲爱的小伙伴们又见面了,上一章我们讲到了
二.函数
1. NumPy 字符串函数
以下函数用于对 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()
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']))
结果:
连接两个字符串:
['hello xyz']
连接示例:
['hello abc' 'hi xyz']
注意不要和np.add()搞混了,这个是实现矩阵的相加的
numpy.char.multiply()
numpy.char.multiply()函数执行多重连接
实例
import numpy as np
print (np.char.multiply('Runoob ',3))
输出结果为:
Runoob Runoob Runoob
实例
import numpy as np
print(np.char.multiply(['1','2','3'], 3))
结果:
['111' '222' '333']
实例:
import numpy as np
a=[['1','2','3'],['4','5','6'],['7','8','9']]
print(np.char.multiply(a, 3))
结果:
[['111' '222' '333']
['444' '555' '666']
['777' '888' '999']]
numpy.char.center()
numpy.char.center() 函数用于将字符串居中,并使用指定字符在左侧和右侧进行填充。
实例
import numpy as np
# np.char.center(str , width,fillchar) :
# str: 字符串,width: 长度,fillchar: 填充字符
print (np.char.center('Runoob', 20,fillchar = '*'))
输出结果为:
*******Runoob*******
numpy.char.capitalize()
numpy.char.capitalize() 函数将字符串的第一个字母转换为大写:
实例
import numpy as np
print (np.char.capitalize('runoob'))
输出结果为:
Runoob
numpy.char.title()
numpy.char.title() 函数将字符串的每个单词的第一个字母转换为大写:
实例
import numpy as np
print (np.char.title('i like runoob'))
输出结果为:
I Like Runoob
numpy.char.lower()
numpy.char.lower() 函数对数组的每个元素转换为小写。它对每个元素调用 str.lower。
实例
import numpy as np
#操作数组
print (np.char.lower(['RUNOOB','GOOGLE']))
# 操作字符串
print (np.char.lower('RUNOOB'))
输出结果为:
['runoob' 'google']
runoob
numpy.char.upper()
numpy.char.upper() 函数对数组的每个元素转换为大写。它对每个元素调用 str.upper。
实例
import numpy as np
#操作数组
print (np.char.upper(['runoob','google']))
# 操作字符串
print (np.char.upper('runoob'))
输出结果为:
['RUNOOB' 'GOOGLE']
RUNOOB
numpy.char.split()
numpy.char.split() 通过指定分隔符对字符串进行分割,并返回数组。默认情况下,分隔符为空格。
实例
import numpy as np
# 分隔符默认为空格
print (np.char.split ('i like runoob?'))
# 分隔符为 .
print (np.char.split ('www.runoob.com', sep = '.'))
输出结果为:
['i', 'like', 'runoob?']
['www', 'runoob', 'com']
注意:如果穿一个参数列表进去情况将会是这样!
import numpy as np
# 分隔符默认为空格
print(np.char.split('i like runoob?'))
# 分隔符为 .
print(np.char.split('www.run,oob.com', sep=['.',',']))
-----------------------------------------------------------------------------------------------------------------
['i', 'like', 'runoob?']
[list(['www', 'run,oob', 'com']) list(['www.run', 'oob.com'])]
numpy.char.splitlines()
import numpy as np
# 换行符 \n
print (np.char.splitlines('i\nlike runoob?'))
print (np.char.splitlines('i\rlike runoob?'))
输出结果为:
['i', 'like runoob?']
['i', 'like runoob?']
- \n,\r,\r\n 都可用作换行符。
numpy.char.strip()
numpy.char.strip() 函数用于移除开头或结尾处的特定字符。
实例
import numpy as np
# 移除字符串头尾的 a 字符
print (np.char.strip('ashok arunooba','a'))
# 移除数组元素头尾的 a 字符
print (np.char.strip(['arunooba','admin','java'],'a'))
输出结果为:
shok arunoob
['runoob' 'dmin' 'jav']
numpy.char.join()
numpy.char.join() 函数通过指定分隔符来连接数组中的元素或字符串
实例
import numpy as np
# 操作字符串
print (np.char.join(':','runoob'))
# 指定多个分隔符操作数组元素
print (np.char.join([':','-'],['runoob','google']))
输出结果为:
r:u:n:o:o:b
['r:u:n:o:o:b' 'g-o-o-g-l-e']
numpy.char.replace()
numpy.char.replace() 函数使用新字符串替换字符串中的所有子字符串。
实例
import numpy as np
print (np.char.replace ('i like runoob', 'oo', 'cc'))
输出结果为:
i like runccb
numpy.char.encode()
numpy.char.encode() 函数对数组中的每个元素调用 str.encode 函数。 默认编码是 utf-8,可以使用标准 Python 库中的编解码器。
实例
import numpy as np
a = np.char.encode('runoob', 'cp500')
print (a)
输出结果为:
b'\x99\xa4\x95\x96\x96\x82'
numpy.char.decode()
numpy.char.decode() 函数对编码的元素进行 str.decode() 解码。
实例
import numpy as np
a = np.char.encode('runoob', 'cp500')
print (a)
print (np.char.decode(a,'cp500'))
输出结果为:
b'\x99\xa4\x95\x96\x96\x82'
runoob
2. NumPy 数学函数
1. 三角函数
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))
输出结果为:
不同角度的正弦值:
[0. 0.5 0.70710678 0.8660254 1. ]
数组中角度的余弦值:
[1.00000000e+00 8.66025404e-01 7.07106781e-01 5.00000000e-01
6.12323400e-17]
数组中角度的正切值:
[0.00000000e+00 5.77350269e-01 1.00000000e+00 1.73205081e+00
1.63312394e+16]
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))
输出结果为:
含有正弦值的数组:
[0. 0.5 0.70710678 0.8660254 1. ]
计算角度的反正弦,返回值以弧度为单位:
[0. 0.52359878 0.78539816 1.04719755 1.57079633]
通过转化为角度制来检查结果:
[ 0. 30. 45. 60. 90.]
arccos 和 arctan 函数行为类似:
[1.00000000e+00 8.66025404e-01 7.07106781e-01 5.00000000e-01
6.12323400e-17]
反余弦:
[0. 0.52359878 0.78539816 1.04719755 1.57079633]
角度制单位:
[ 0. 30. 45. 60. 90.]
tan 函数:
[0.00000000e+00 5.77350269e-01 1.00000000e+00 1.73205081e+00
1.63312394e+16]
反正切:
[0. 0.52359878 0.78539816 1.04719755 1.57079633]
角度制单位:
[ 0. 30. 45. 60. 90.]
2. 舍入函数
numpy.around() 函数返回指定数字的四舍五入值。
numpy.around(a,decimals)
参数说明:
- a: 数组
- decimals: 舍入的小数位数。 默认值为0。 如果为负,整数将四舍五入到小数点左侧的位置
实例
import numpy as np
a = 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))
输出结果为:
原数组:
[ 1. 5.55 123. 0.567 25.532]
舍入后:
[ 1. 6. 123. 1. 26.]
[ 1. 5.6 123. 0.6 25.5]
[ 0. 10. 120. 0. 30.]
numpy.floor()
numpy.floor() 返回小于或者等于指定表达式的最大整数,即向下取整。
实例
import numpy as np
a = np.array([-1.7, 1.5, -0.2, 0.6, 10])
print ('提供的数组:')
print (a)
print ('\n')
print ('修改后的数组:')
print (np.floor(a))
输出结果为:
提供的数组:
[-1.7 1.5 -0.2 0.6 10. ]
修改后的数组:
[-2. 1. -1. 0. 10.]
numpy.ceil()
numpy.ceil() 返回大于或者等于指定表达式的最小整数,即向上取整。
实例
import numpy as np
a = np.array([-1.7, 1.5, -0.2, 0.6, 10])
print ('提供的数组:')
print (a)
print ('\n')
print ('修改后的数组:')
print (np.ceil(a))
输出结果为:
提供的数组:
[-1.7 1.5 -0.2 0.6 10. ]
修改后的数组:
[-1. 2. -0. 1. 10.]
3. NumPy 算术函数
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))
输出结果为:
第一个数组:
[[0. 1. 2.]
[3. 4. 5.]
[6. 7. 8.]]
第二个数组:
[10 10 10]
两个数组相加:
[[10. 11. 12.]
[13. 14. 15.]
[16. 17. 18.]]
两个数组相减:
[[-10. -9. -8.]
[ -7. -6. -5.]
[ -4. -3. -2.]]
两个数组相乘:
[[ 0. 10. 20.]
[30. 40. 50.]
[60. 70. 80.]]
两个数组相除:
[[0. 0.1 0.2]
[0.3 0.4 0.5]
[0.6 0.7 0.8]]
此外 Numpy 也包含了其他重要的算术函数。
numpy.reciprocal()
numpy.reciprocal() 函数返回参数逐元素的倒数。如 1/4 倒数为 4/1。
实例
import numpy as np
a = np.array([0.25, 1.33, 1, 100])
print ('我们的数组是:')
print (a)
print ('\n')
print ('调用 reciprocal 函数:')
print (np.reciprocal(a))
输出结果为:
我们的数组是:
[ 0.25 1.33 1. 100. ]
调用 reciprocal 函数:
[4. 0.7518797 1. 0.01 ]
numpy.power()
numpy.power() 函数将第一个输入数组中的元素作为底数,计算它与第二个输入数组中相应元素的幂。
实例
import numpy as np
a = 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))
输出结果为:
我们的数组是;
[ 10 100 1000]
调用 power 函数:
[ 100 10000 1000000]
第二个数组:
[1 2 3]
再次调用 power 函数:
[ 10 10000 1000000000]
numpy.mod()
实例
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))
输出结果为:
第一个数组:
[10 20 30]
第二个数组:
[3 5 7]
调用 mod() 函数:
[1 0 2]
调用 remainder() 函数:
[1 0 2]
4. NumPy 统计函数
NumPy 提供了很多统计函数,用于从数组中查找最小元素,最大元素,百分位标准差和方差等。 函数说明如下:
numpy.amin() 和 numpy.amax()
numpy.amin() 用于计算数组中的元素沿指定轴的最小值。
numpy.amax() 用于计算数组中的元素沿指定轴的最大值。
numpy.amin() 和 numpy.amax()
实例
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))
输出结果为:
我们的数组是:
[[3 7 5]
[8 4 3]
[2 4 9]]
调用 amin() 函数:
[3 3 2]
再次调用 amin() 函数:
[2 4 3]
调用 amax() 函数:
9
再次调用 amax() 函数:
[8 7 9]
numpy.ptp()
numpy.ptp()函数计算数组中元素最大值与最小值的差(最大值 - 最小值)。
实例
import numpy as np
a = 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))
输出结果为:
我们的数组是:
[[3 7 5]
[8 4 3]
[2 4 9]]
调用 ptp() 函数:
7
沿轴 1 调用 ptp() 函数:
[4 5 7]
沿轴 0 调用 ptp() 函数:
[6 3 6]
numpy.percentile()
百分位数是统计中使用的度量,表示小于这个值的观察值的百分比。 函数numpy.percentile()接受以下参数。
numpy.percentile(a, q, axis)
参数说明:
- a: 输入数组
- q: 要计算的百分位数,在 0 ~ 100 之间
- axis: 沿着它计算百分位数的轴
首先明确百分位数:
第 p 个百分位数是这样一个值,它使得至少有 p% 的数据项小于或等于这个值,且至少有 (100-p)% 的数据项大于或等于这个值。
举个例子:高等院校的入学考试成绩经常以百分位数的形式报告。比如,假设某个考生在入学考试中的语文部分的原始分数为 54 分。相对于参加同一考试的其他学生来说,他的成绩如何并不容易知道。但是如果原始分数54分恰好对应的是第70百分位数,我们就能知道大约70%的学生的考分比他低,而约30%的学生考分比他高。
这里的 p = 70。
实例
import numpy as np
a = 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))
输出结果为:
我们的数组是:
[[10 7 4]
[ 3 2 1]]
调用 percentile() 函数:
3.5
[6.5 4.5 2.5]
[7. 2.]
[[7.]
[2.]]
numpy.median()
numpy.median() 函数用于计算数组 a 中元素的中位数(中值)
实例
import numpy as np
a = 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))
输出结果为:
我们的数组是:
[[30 65 70]
[80 95 10]
[50 90 60]]
调用 median() 函数:
65.0
沿轴 0 调用 median() 函数:
[50. 90. 60.]
沿轴 1 调用 median() 函数:
[65. 80. 60.]
numpy.mean()
numpy.mean() 函数返回数组中元素的算术平均值。 如果提供了轴,则沿其计算。
算术平均值是沿轴的元素的总和除以元素的数量。
实例
import numpy as np
a = np.array([[1,2,3],[3,4,5],[4,5,6]])
print ('我们的数组是:')
print (a)
print ('\n')
print ('调用 mean() 函数:')
print (np.mean(a))
print ('\n')
print ('沿轴 0 调用 mean() 函数:')
print (np.mean(a, axis = 0))
print ('\n')
print ('沿轴 1 调用 mean() 函数:')
print (np.mean(a, axis = 1))
输出结果为:
我们的数组是:
[[1 2 3]
[3 4 5]
[4 5 6]]
调用 mean() 函数:
3.6666666666666665
沿轴 0 调用 mean() 函数:
[2.66666667 3.66666667 4.66666667]
沿轴 1 调用 mean() 函数:
[2. 4. 5.]
numpy.average()
numpy.average() 函数根据在另一个数组中给出的各自的权重计算数组中元素的加权平均值。
该函数可以接受一个轴参数。 如果没有指定轴,则数组会被展开。
加权平均值即将各数值乘以相应的权数,然后加总求和得到总体值,再除以总的单位数。
考虑数组[1,2,3,4]和相应的权重[4,3,2,1],通过将相应元素的乘积相加,并将和除以权重的和,来计算加权平均值。
加权平均值 = (1*4+2*3+3*2+4*1)/(4+3+2+1)
实例
import numpy as np
a = 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))
输出结果为:
我们的数组是:
[1 2 3 4]
调用 average() 函数:
2.5
再次调用 average() 函数:
2.0
权重的和:
(2.0, 10.0)
6. 标准差
标准差是一组数据平均值分散程度的一种度量。
标准差是方差的算术平方根。
标准差公式如下:
std = sqrt(mean((x - x.mean())**2))
如果数组是 [1,2,3,4],则其平均值为 2.5。 因此,差的平方是 [2.25,0.25,0.25,2.25],并且再求其平均值的平方根除以 4,即 sqrt(5/4) ,结果为 1.1180339887498949。
实例
import numpy as np
print (np.std([1,2,3,4]))
输出结果为:
1.1180339887498949
7. 方差
统计中的方差(样本方差)是每个样本值与全体样本值的平均数之差的平方值的平均数,即 mean((x - x.mean())** 2)。
换句话说,标准差是方差的平方根。
实例
import numpy as np
print (np.var([1,2,3,4]))
输出结果为:
1.25
8.线性代数
外积 numpy.outer
笛卡尔积numpy.meshgrid()
5. NumPy 排序、条件刷选函数
numpy.sort()
NumPy 提供了多种排序的方法。 这些排序函数实现不同的排序算法,每个排序算法的特征在于执行速度,最坏情况性能,所需的工作空间和算法的稳定性。 下表显示了三种排序算法的比较。
种类 | 速度 | 最坏情况 | 工作空间 | 稳定性 |
---|---|---|---|---|
‘quicksort’(快速排序) | 1 | O(n^2) | 0 | 否 |
‘mergesort’(归并排序) | 2 | O(n*log(n)) | ~n/2 | 是 |
‘heapsort’(堆排序) | 3 | O(n*log(n)) | 0 | 否 |
numpy.argsort()
numpy.sort() 函数返回输入数组的排序副本。函数格式如下:
numpy.sort(a, axis, kind, order)
参数说明:
- a: 要排序的数组
- axis: 沿着它排序数组的轴,如果没有数组会被展开,沿着最后的轴排序, axis=0 按列排序,axis=1 按行排序
- kind: 默认为’quicksort’(快速排序)
- order: 如果数组包含字段,则是要排序的字段
实例
import numpy as np
a = np.array([[3,7],[9,1]])
print ('我们的数组是:')
print (a)
print ('\n')
print ('调用 sort() 函数:')
print (np.sort(a))
print ('\n')
print ('按列排序:')
print (np.sort(a, axis = 0))
print ('\n')
# 在 sort 函数中排序字段
dt = np.dtype([('name', 'S10'),('age', int)])
a = np.array([("raju",21),("anil",25),("ravi", 17), ("amar",27)], dtype = dt)
print ('我们的数组是:')
print (a)
print ('\n')
print ('按 name 排序:')
print (np.sort(a, order = 'name'))
输出结果为:
我们的数组是:
[[3 7]
[9 1]]
调用 sort() 函数:
[[3 7]
[1 9]]
按列排序:
[[3 1]
[9 7]]
我们的数组是:
[(b'raju', 21) (b'anil', 25) (b'ravi', 17) (b'amar', 27)]
按 name 排序:
[(b'amar', 27) (b'anil', 25) (b'raju', 21) (b'ravi', 17)]
numpy.lexsort()
numpy.lexsort() 用于对多个序列进行排序。把它想象成对电子表格进行排序,每一列代表一个序列,排序时优先照顾靠后的列。
这里举一个应用场景:小升初考试,重点班录取学生按照总成绩录取。在总成绩相同时,数学成绩高的优先录取,在总成绩和数学成绩都相同时,按照英语成绩录取…… 这里,总成绩排在电子表格的最后一列,数学成绩在倒数第二列,英语成绩在倒数第三列。
实例
import numpy as np
nm = ('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])
输出结果为:
调用 lexsort() 函数:
[3 1 0 2]
使用这个索引来获取排序后的数据:
['amar, f.y.', 'anil, s.y.', 'raju, f.y.', 'ravi, s.y.']
上面传入 np.lexsort 的是一个tuple,排序时首先排 nm,顺序为:amar、anil、raju、ravi 。综上排序结果为 [3 1 0 2]。
msort、sort_complex、partition、argpartition
函数 | 描述 |
---|---|
msort(a) | 数组按第一个轴排序,返回排序后的数组副本。np.msort(a) 相等于 |
sort_complex(a) | 对复数按照先实部后虚部的顺序进行排序。 |
partition(a, kth[, axis, kind, order]) | 指定一个数,对数组进行分区 |
argpartition(a, kth[, axis, kind, order]) | 可以通过关键字 kind 指定算法沿着指定轴对 |
复数排序: |
import numpy as np
np.sort_complex([5, 3, 6, 2, 1])
array([ 1.+0.j, 2.+0.j, 3.+0.j, 5.+0.j, 6.+0.j])np.sort_complex([1 + 2j, 2 - 1j, 3 - 2j, 3 - 3j, 3 + 5j])
array([ 1.+2.j, 2.-1.j, 3.-3.j, 3.-2.j, 3.+5.j])
partition() 分区排序:
a = np.array([3, 4, 2, 1])
np.partition(a, 3) # 将数组 a 中所有元素(包括重复元素)从小到大排列,3 表示的是排序数组索引为 3 的数字,比该数字小的排在该数字前面,比该数字大的排在该数字的后面
array([2, 1, 3, 4])np.partition(a, (1, 3)) # 小于 1 的在前面,大于 3 的在后面,1和3之间的在中间
array([1, 2, 3, 4])
找到数组的第 3 小(index=2)的值和第 2 大(index=-2)的值
arr = np.array([46, 57, 23, 39, 1, 10, 0, 120])
arr[np.argpartition(arr, 2)[2]]
10
arr[np.argpartition(arr, -2)[-2]]
57
同时找到第 3 和第 4 小的值。注意这里,用 [2,3] 同时将第 3 和第 4 小的排序好,然后可以分别通过下标 [2] 和 [3] 取得。
arr[np.argpartition(arr, [2,3])[2]]
10
arr[np.argpartition(arr, [2,3])[3]]
23
numpy.argmax() 和 numpy.argmin()
numpy.argmax() 和 numpy.argmin()函数分别沿给定轴返回最大和最小元素的索引。
实例:
import numpy as np
a = np.array([[30,40,70],[80,20,10],[50,90,60]])
print ('我们的数组是:')
print (a)
print ('\n')
print ('调用 argmax() 函数:')
print (np.argmax(a))
print ('\n')
print ('展开数组:')
print (a.flatten())
print ('\n')
print ('沿轴 0 的最大值索引:')
maxindex = np.argmax(a, axis = 0)
print (maxindex)
print ('\n')
print ('沿轴 1 的最大值索引:')
maxindex = np.argmax(a, axis = 1)
print (maxindex)
print ('\n')
print ('调用 argmin() 函数:')
minindex = np.argmin(a)
print (minindex)
print ('\n')
print ('展开数组中的最小值:')
print (a.flatten()[minindex])
print ('\n')
print ('沿轴 0 的最小值索引:')
minindex = np.argmin(a, axis = 0)
print (minindex)
print ('\n')
print ('沿轴 1 的最小值索引:')
minindex = np.argmin(a, axis = 1)
print (minindex)
输出结果为:
我们的数组是:
[[30 40 70]
[80 20 10]
[50 90 60]]
调用 argmax() 函数:
7
展开数组:
[30 40 70 80 20 10 50 90 60]
沿轴 0 的最大值索引:
[1 2 0]
沿轴 1 的最大值索引:
[2 0 1]
调用 argmin() 函数:
5
展开数组中的最小值:
10
沿轴 0 的最小值索引:
[0 1 1]
沿轴 1 的最小值索引:
[0 2 0]
numpy.nonzero()
numpy.nonzero() 函数返回输入数组中非零元素的索引。
实例
import numpy as np
a = np.array([[30,40,0],[0,20,10],[50,0,60]])
print ('我们的数组是:')
print (a)
print ('\n')
print ('调用 nonzero() 函数:')
print (np.nonzero (a))
输出结果为:
我们的数组是:
[[30 40 0]
[ 0 20 10]
[50 0 60]]
调用 nonzero() 函数:
(array([0, 0, 1, 1, 2, 2]), array([0, 1, 1, 2, 0, 2]))
numpy.where()
numpy.where() 函数返回输入数组中满足给定条件的元素的索引。
实例
import numpy as np
x = np.arange(9.).reshape(3, 3)
print ('我们的数组是:')
print (x)
print ( '大于 3 的元素的索引:')
y = np.where(x > 3)
print (y)
print ('使用这些索引来获取满足条件的元素:')
print (x[y])
输出结果为:
我们的数组是:
[[0. 1. 2.]
[3. 4. 5.]
[6. 7. 8.]]
大于 3 的元素的索引:
(array([1, 1, 2, 2, 2]), array([1, 2, 0, 1, 2]))
使用这些索引来获取满足条件的元素:
[4. 5. 6. 7. 8.]
numpy.extract()
numpy.extract() 函数根据某个条件从数组中抽取元素,返回满条件的元素。
实例
import numpy as np
x = np.arange(9.).reshape(3, 3)
print ('我们的数组是:')
print (x)
# 定义条件, 选择偶数元素
condition = np.mod(x,2) == 0
print ('按元素的条件值:')
print (condition)
print ('使用条件提取元素:')
print (np.extract(condition, x))
输出结果为:
我们的数组是:
[[0. 1. 2.]
[3. 4. 5.]
[6. 7. 8.]]
按元素的条件值:
[[ True False True]
[False True False]
[ True False True]]
使用条件提取元素:
[0. 2. 4. 6. 8.]