Numpy的一些函数

332 阅读11分钟

字符串函数

用于对dtype为numpy.string_或numpy.unicode_的数组执行向量化字符串操作,基于Python内置库的标准字符串函数在字符数组类(numpy.char)中的定义

add()

对两个数组的元素进行字符串连接

import numpy as np

print(np.char.add(['you'],['666']))
print(np.char.add(['incredible','come'],['today','on']))

'''
输出:
['you666']
['incredibletoday' 'comeon']
'''

multiply()

返回重连接元素后的字符串

import numpy as np

print(np.char.multiply(['nice'],3))

'''
输出:
['nicenicenice']
'''

center()

讲字符串居中,并使用指定字符在左侧和右侧进行填充

import numpy as np

print(np.char.center(["who","I","am"],11,fillchar='#'))

'''
输出:
['####who####' '#####I#####' '#####am####']
'''

capitalize()

将字符串第一个字母转为大写

import numpy as np

# 不管字符串中有多少字母是大写,最终输出的字符串只有首字母是大写
print(np.char.capitalize(["one By oNe"]))

'''
输出:
['One by one']
'''

title()

将每个字符串每个单词的第一个字母转成大写

import numpy as np

print(np.char.title(["hand in hand with python"]))
'''
输出:
['Hand In Hand With Python']
'''

lower()

数组元素转换为小写

import numpy as np

print(np.char.lower(["Hand In Hand With Python"]))

'''
输出:
['hand in hand with python']
'''

upper()

数组元素转换为大写

import numpy as np

print(np.char.upper(["hand in hand with python"]))

'''
输出:
['HAND IN HAND WITH PYTHON']
'''

split()

指定分隔符对指定字符串进行分割,并返回数组列表

print(np.char.split(["one by one","hand in hand with python"]))

'''
输出:
[list(['one', 'by', 'one']) list(['hand', 'in', 'hand', 'with', 'python'])]
'''

splitlines()

返回元素中的行列表,以换行符分割

print(np.char.splitlines(["one by one","hand in hand with python"]))
print(np.char.splitlines(["one by \none","hand in hand \nwith python"]))

'''
输出:
[list(['one by one']) list(['hand in hand with python'])]
[list(['one by ', 'one']) list(['hand in hand ', 'with python'])]
'''

strip()

除去元素开头或结尾处的特定字符

print(np.char.strip(["one **by*** one","***hand in hand with python***"],chars='*'))

'''
输出:
['one **by*** one' 'hand in hand with python']
'''

replace()

使用新字符串替换字符串中的所有子字符串

print(np.char.replace(["one by one","hand in hand with python"],"python","c++"))

'''
输出:
['one by one' 'hand in hand with c++']
'''

encode() 和 decode()

encode():编码,数组元素依次调用str.encode
decode():解码,数组元素依次调用str.decode

arr = (np.char.encode(["you","666"],'utf-8'))
print("encode output:",arr)
# 用什么编码就用什么解码
print("decode output:",np.char.decode(arr,'utf-8'))

'''
输出:
encode output: [b'you' b'666']
decode output: ['you' '666']
'''

数学函数

标准的三角函数sin()、cos()、tan()

import numpy as np

arr = np.array([0,30,45,60,90])
print('不同角度的正弦值:')

# 通过乘 "pi/180" 转成弧度
print(np.sin(arr * np.pi/180),'\n')

print('不同角度的余弦值:')
print(np.cos(arr * np.pi/180),'\n')

print('不同角度的正切值:')
print(np.tan(arr * np.pi/180),'\n')

'''
输出:
不同角度的正弦值:
[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()

import numpy as np

arr = np.array([0,30,45,60,90])
print('含正弦值的数组:')
sin = np.sin(arr * np.pi/180)
print(sin,'\n')

print('计算角度的反正弦,返回值以弧度为单位:')
inv = np.arcsin(sin)
print(inv,'\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.]
'''

print('arccos 和 arctan 函数行为类似:')
cos = np.cos(arr * np.pi/180)
print(cos,'\n')

print('===== 反余弦:')
inv = np.arccos(cos)
print(inv,'\n')

print(np.degrees(inv),'\n')
print('-------------------')
tan = np.tan(arr * np.pi/180)
print(tan,'\n')

print('===== 反正切:')
inv = np.arctan(tan)
print(inv,'\n')

print(np.degrees(inv))

'''
输出:
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.] 

-------------------
[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.]
'''

around()

原型:numpy.around(a,decimals=0)
作用:返回指定数字的四舍五入值

参数描述
a数组
decimals舍入的小数位数。默认值为0。如果为负数,整数将四舍五入到小数左侧的位置
import numpy as np

x = np.array([0,0.2212123,2,-123.6666,12.23245])
print(np.around(x))
print(np.around(x,decimals=2))
print(np.around(x,decimals=-1))

'''
输出:
[   0.    0.    2. -124.   12.]
[   0.      0.22    2.   -123.67   12.23]
[   0.    0.    0. -120.   10.]
'''

floor()

作用:向下取整,返回不大于输入参数的最大整数。即标量x的下限是最大的整数i,使得i<=x。注意在Python中,向下取整总是从0舍入。

import numpy as np

x = np.array([1,1.66,2.1,-3.3,0.6])
print(np.floor(x),'\n')

'''
输出:
[ 1.  1.  2. -4.  0.] 

[ 1.  2.  3. -3.  1.]

'''

ceil()

作用:向上取整,返回输入值的上限,即:标量x的上限是最小的整数i,使得i>=x。

import numpy as np

x = np.array([1,1.66,2.1,-3.3,0.6])
print(np.ceil(x),'\n')

'''
输出:
[ 1.  2.  3. -3.  1.]

'''

算术运算

add()、subtract()、multiply()、divide()

作用:加减乘除

import numpy as np

x = np.arange(9,dtype="f").reshape(3,3)
print(x,'\n')

y = np.array([1,2,3])
print(y,'\n')

# 减、乘、除同理
print(np.add(x,y))
print('==========')
print(x + y)

'''
输出:
[[0. 1. 2.]
 [3. 4. 5.]
 [6. 7. 8.]] 

[1 2 3] 

[[ 1.  3.  5.]
 [ 4.  6.  8.]
 [ 7.  9. 11.]]
==========
[[ 1.  3.  5.]
 [ 4.  6.  8.]
 [ 7.  9. 11.]]
'''

reciprocal()

作用:返回参数逐个元素的倒数

import numpy as np

x = np.array([0.25,0.5,1,100])
print(np.reciprocal(x))

'''
输出:
[4.   2.   1.   0.01]
'''

power()

作用:讲一个输入数组中的元素作为底数,计算它与第二个数组中相应元素的幂,注意两个数组元素个数要一致。

import numpy as np

x = np.array([2,2,2])
y = np.array([1,2,3])

print(np.power(x,y))

'''
输出:
[ 2 4 8]
'''

mod()、remainder()

作用:计算输入数组中相应元素的相除后的余数

x = np.array([10,10,10])
y = np.array([1,2,3])

print(np.mod(x,y))
print(np.remainder(x,y))

'''
输出:
[0 0 1]
[0 0 1]
'''

统计函数

amax()、amin()

作用:计算数组中的元素沿指定轴的最大值、最小值

import numpy as np

x = np.random.randint(1,11,9).reshape(3,3)
print(x)
# 列中元素的最小值
print('列中元素的最小值:',np.amin(x,0),'\n')

# 行中元素的最小值
print('行中元素的最小值:',np.amin(x,1),'\n')

print('列中元素的最大值:',np.amax(x,0),'\n')

print('行中元素的最大值:',np.amax(x,1))
'''
输出:
列中元素的最小值: [3 5 2] 

行中元素的最小值: [5 2 7] 

列中元素的最大值: [ 9 10  7] 

行中元素的最大值: [10  5  9]
'''

ptp()

作用:计算数组中元素最大与最小值的差(最大值 - 最小值)

import numpy as np

x = np.random.randint(1,11,9).reshape(3,3)
print(x)

print('数组中最大值与最小值的差:',np.ptp(x))
print('数组中列元素最大值与最小值的差:',np.ptp(x,0))
print('数组中行元素最大值与最小值的差:',np.ptp(x,0))
'''
输出:
[[ 4  9  4]
 [ 3  8 10]
 [ 4  9  9]]
数组中最大值与最小值的差: 7
数组中列元素最大值与最小值的差: [1 1 6]
数组中行元素最大值与最小值的差: [1 1 6]

percentile()

原型:numpy.percentile(a,q,axis) 作用:百分位数是统计中使用的度量,表示小于这个值的观察值的百分比

参数描述
a输入数组
p要计算的百分位数,在0~100之间
axis沿着它计算百分位数的轴
import numpy as np

x = np.array([[1,2,5],[3,6,5]])
print(x,'\n')
print(np.percentile(x,50),'\n')
# 列
print(np.percentile(x,50,axis=0),'\n')
# 行
print(np.percentile(x,50,axis=1))

'''
输出:
[[1 2 5]
 [3 6 5]] 

4.0 

[2. 4. 5.] 

[2. 5.]
'''

median()

作用:算数组中元素的中位数(中值)

import numpy as np
x = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(x,'\n')
print(np.median(x))
# 列
print(np.median(x,axis=0))
# 行
print(np.median(x,axis=1))

'''
输出:
[[1 2 3]
 [4 5 6]
 [7 8 9]] 

5.0
[4. 5. 6.]
[2. 5. 8.]
’‘’

mean()

作用:返回数组中元素的算术平均值。如果提供了轴,则沿其计算。

import numpy as np
x = np.arange(1,10).reshape(3,3)
print(x,'\n')
print(np.mean(x))
print(np.mean(x,axis=0))
print(np.mean(x,axis=1))

'''
输出:
[[1 2 3]
 [4 5 6]
 [7 8 9]] 

5.0
[4. 5. 6.]
[2. 5. 8.]
'''

average()

作用根据在另一个数组中给出各自的权重,计算数组中元素的加权平均值,可以接受一个轴参数。如果没有指定轴,则数组会被展开。

加权平均值: 将各数值乘以相应的权数,然后加总求和得到总体值,再除以总的单位数。
例子:考虑数组[1,2,3,4]和相应的权重[4,3,2,1],通过将相应元素的乘积相加,并将和除以权重的和,来计算加权平均值。
加权平均值 = (14+23+32+41)/(4+3+2+1)

import numpy as np
x = np.array([1,2,3,4])
print(x)

print('x的平均值:',np.average(x),'\n') 
wts = np.array([4,3,2,1])

print('加权平均值:',np.average(x,weights=wts))
# (4+6+6+4)/(4+3+2+1) = 2.0

# 如果 returned 参数设置为 true,则返回权重的和
print('权重的和:',np.average(x,weights=wts,returned='true'))

'''
输出:

x的平均值: 2.5 

加权平均值: 2.0
权重的和:(2.0, 10.0)
'''

# 多维数组中的运用
import numpy as np
x = np.array([0,1,2,3,4,5]).reshape(3,2)
print(x,'\n')

wts = np.array([3,5])
print(np.average(x,axis=1,weights=wts)) # 这里axis=0会报错,因为x列元素有3个,权重只有2个。
'''
输出:
[[0 1]
 [2 3]
 [4 5]]
 
[0.625 2.625 4.625]
'''

标准差

标准差是一组数据平均值分散程度的一种度量
标准差是方差的算术平方根
公式: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),sqrt(5/4)意思就是1.25{{\sqrt{1.25}}},结果为:1.118033988749895。

import numpy as np
print(np.std([1,2,3,4]))
'''
输出:
1.118033988749895 
'''
# 求标准差过程:
x = np.array([1,2,3,4])
# x - x.mean()
print(x - np.mean(x))
y = np.array([2.25,0.25,0.25,2.25])
ym = np.mean(y)
print(np.sqrt(ym))

方差

统计中的方差(样本方差)是每个样本值与全体样本值的平均数之差的平均值的平均数,即mean((x - x.mean())**2)。换句话说,标准差是方差的平均根。差的平方是[2.25,0.25,0.25,2.25],并且其平均值的平方根除以4。

import numpy as np
print(np.var([1,2,3,4]))

'''
输出:
1.25
'''
# 求方差过程:
x = np.array([1,2,3,4])
# x - x.mean()
print(x - np.mean(x))
y = np.array([2.25,0.25,0.25,2.25])
ym = np.mean(y)

排列函数

种类速度最坏情况工作空间稳定性
'quicksort'(快速排序)1O(n^2)0
'mergesort'(归并排序)2O(n*log(n))~n/2
'heapsort'(堆排序)3O(n*log(n))0

sort()

原型:sort(a,axis,kind,order)
功能:返回输入数组的排序副本

参数描述
a要排序的数组
axis沿着它排序数组的轴,如果没有数组会被展开,沿着最后的轴排序,axis=0按列排序,axis=1按行排序
kind排序算法,默认为'quicksort'
order如果数组中包含字段,则是要排序字段
import numpy as np
x = np.random.randint(1,11,12).reshape(3,4)
#print(x,'\n')

a = np.sort(x)
#print(a,'\n')

b = np.sort(x,axis=0)
print(b,'\n')

dt = np.dtype([("name","S10"),("age",int)])
y = np.array([("liudh",61),("jackzhang",60)],dtype=dt)
print(y)

c = np.sort(y,order="age")
print(c)

'''
输出:

[[2 3 6 8]
 [1 6 7 8]
 [3 4 6 9]] 

[[2 1 3 6]
 [3 4 6 8]
 [7 6 8 9]] 

[(b'liudh', 61) (b'jackzhang', 60)]
[(b'jackzhang', 60) (b'liudh', 61)]
'''

argsort()

作用:对输入数组沿给定轴执行间接排序,并使用指定排序类型返回数据的索引数组。这个索引数组用于结构排序后的数组。

import numpy as np
x = np.array([2,1,3])
a = np.argsort(x)
print('a:',a)
print(x[a])

'''
输出:
a: [1 0 2]
[1 2 3]
'''

partition(a,kth[,axis,kind,order])

作用:指定一个数,对数组进行分区

import numpy as np

x = np.array([1,5,3,2,6,7,4])

print(np.partition(x,3))
# 2~5之间的数放到2和5之间 小于2的数放到2的前面,大于5的数放在5的后面
print(np.partition(x,(2,5)))

'''
输出:
[1 2 3 4 5 7 6]
[1 2 3 4 5 6 7]
'''

argpartition(a,kth(,axis,kind,order))

作用:可以通过关键字 kind 指定算法沿着指定轴对数组进行分区

x = np.array([1,3,2,5,7,10,9])
# 数组的是数组下标 “2”是指第3小
print(np.argpartition(x,2))
# 数组的是数组下标 “-2”是指第2大
print(np.argpartition(x,-2),'\n')

print(x[np.argpartition(x,2)])
print(x[np.argpartition(x,2)[2]],'\n')

print(x[np.argpartition(x,-2)])
print(x[np.argpartition(x,-2)[-2]])

'''
输出:
[0 2 1 3 4 5 6]
[1 0 2 3 4 6 5] 

[ 1  2  3  5  7 10  9]
3 

[ 3  1  2  5  7  9 10]
9
'''

搜索函数

max()、min()

作用:沿着给定轴返回最大或最小值

import numpy as np
y = np.array([[3,5,6],[1,2,10],[9,10,13]])
print(y,'\n')
# print(y.flatten())
print(np.max(y))
print(np.max(y,axis=0))
print(np.max(y,axis=1))
'''
输出:
[[ 3  5  6]
 [ 1  2 10]
 [ 9 10 13]] 

13
[ 9 10 13]
[ 6 10 13]
'''
# 搜索最小值同理
...

argmax()、argmin()

作用:沿着给定轴返回最大或最小值索引

import numpy as np
y = np.array([[3,5,6],[1,12,10],[9,10,13]])
print(y,'\n')

print(np.argmax(y))
print(np.argmax(y,axis=0))
print(np.argmax(y,axis=1))

'''
输出:
[[ 3  5  6]
 [ 1 12 10]
 [ 9 10 13]] 

8
[2 1 2]
[2 1 2]
'''

nonzero()

作用:返回非零元素的索引

import numpy as np
y = np.array([[0,5,6],[1,12,10],[9,10,13]])
print(y,'\n')
print(np.nonzero(y))
'''
输出:
[[ 0  5  6]
 [ 1 12 10]
 [ 9 10 13]] 
# 说明:行,行中的第几个元素索引
(array([0, 0, 1, 1, 1, 2, 2, 2]), array([1, 2, 0, 1, 2, 0, 1, 2]))
'''

where()

作用:返回输入数组中满足给定条件的元素的索引

import numpy as np
y = np.array([[0,5,6],[1,12,10],[9,10,13]])
print(y,'\n')
print(np.where(y>9))
'''
输出:
[[ 0  5  6]
 [ 1 12 10]
 [ 9 10 13]] 
# 说明:行,行中的第几个元素索引,从0开始
(array([1, 1, 2, 2]), array([1, 2, 1, 2]))
'''

extract()

作用:根据某个条件从数组中抽取元素,返回满足条件的元素

import numpy as np
y = np.array([[0,5,6],[1,12,10],[9,10,13]])
print(y,'\n')
con = np.mod(y,2) == 0
print(con)
print(np.extract(con,y))
'''
输出:
[[ 0  5  6]
 [ 1 12 10]
 [ 9 10 13]] 

[[ True False  True]
 [False  True  True]
 [False  True False]]
[ 0  6 12 10 10]
'''