Numpy入门(二)Numpy常用函数
程序员文章站
2023-12-27 18:13:09
...
常用函数
1 文件读写
import numpy as np
i2 = np.eye(2)
i2
array([[1., 0.],
[0., 1.]])
i2.dtype
dtype('float64')
np.savetxt('eye.txt',i2)
2 CSV文件读写
可以看到,使用逗号分隔符,usecols指定了特定的列,unpack表示将选择的列拆分成多个数据,分别接收
c,v = np.loadtxt('data.csv',delimiter=',',usecols=(6,7),unpack = True)
c
336.1
v
21144800.0
3 成交量加权平均价格(VWAP)
vwap = np.average(c,weights =v)
vwap
336.1
mean = np.mean(c)
mean
336.1
4 取值范围
h,l = np.loadtxt('data.csv',delimiter=',',usecols =(4,5),unpack = True)
h
344.4
l
333.53
np.max(h)
344.4
np.min(l)
333.53
np.ptp(h)
0.0
median = np.median(c)
median
336.1
a = np.random.randn(10)
a
array([-0.91366364, 0.56874779, 1.93163306, -1.20680229, 0.61898735,
-0.03009919, 1.0977881 , -1.69915867, -0.54960063, -0.38438985])
sorted_close = np.msort(a)
sorted_close
array([-1.69915867, -1.20680229, -0.91366364, -0.54960063, -0.38438985,
-0.03009919, 0.56874779, 0.61898735, 1.0977881 , 1.93163306])
np.median(a)
-0.20724452344036656
np.mean(a)
-0.05665579774572808
np.var(a)
1.123988115028372
np.diff(a)
array([ 1.48241142, 1.36288528, -3.13843535, 1.82578963, -0.64908654,
1.1278873 , -2.79694677, 1.14955804, 0.16521078])
a
array([-0.91366364, 0.56874779, 1.93163306, -1.20680229, 0.61898735,
-0.03009919, 1.0977881 , -1.69915867, -0.54960063, -0.38438985])
returns = np.diff(a)/a[:-1]
returns
array([ -1.62249143, 2.39629113, -1.62475752, -1.51291529,
-1.04862651, -37.47234271, -2.54780204, -0.67654543,
-0.30060151])
np.std(returns)
11.57815124733535
np.where(returns>0)
(array([1]),)
np.sqrt(1/12)
0.0
np.sqrt (1./12)
0.28867513459481287
a = np.arange(10)
indices = np.where(a>5)
np.take(a,indices)
array([[6, 7, 8, 9]])
np.argmin(a)
0
np.argmax(a)
9
np.ones(5)
array([1., 1., 1., 1., 1.])
a = np.ones(10)
a.fill(5)
a
array([5., 5., 5., 5., 5., 5., 5., 5., 5., 5.])
np.ones(shape=(2,3),dtype = np.int32)
array([[1, 1, 1],
[1, 1, 1]], dtype=int32)
np.dot 如果处理的是一维数据,那么就是点积,如果处理二维数据,就是矩阵的乘积
a = np.arange(9)
b = np.arange(9)
np.dot(a,b)
204
a = a.reshape(3,3)
a
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
b = b.reshape(3,3)
np.dot(a,b)
array([[ 15, 18, 21],
[ 42, 54, 66],
[ 69, 90, 111]])
b.clip(3,6)
array([[3, 3, 3],
[3, 4, 5],
[6, 6, 6]])
a = np.arange(9)
a.compress(a>2)
array([3, 4, 5, 6, 7, 8])
a = np.arange(1,9)
a.prod()
40320
a.cumprod()
array([ 1, 2, 6, 24, 120, 720, 5040, 40320])