- 导入numpy库并简写为 np
import numpy as np
- 打印numpy的版本和配置说明
print(np.__version__)
np.show_config()
1.15.4
mkl_info:
libraries = ['mkl_rt', 'pthread']
library_dirs = ['/anaconda3/lib']
define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
include_dirs = ['/anaconda3/include']
blas_mkl_info:
libraries = ['mkl_rt', 'pthread']
library_dirs = ['/anaconda3/lib']
define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
include_dirs = ['/anaconda3/include']
blas_opt_info:
libraries = ['mkl_rt', 'pthread']
library_dirs = ['/anaconda3/lib']
define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
include_dirs = ['/anaconda3/include']
lapack_mkl_info:
libraries = ['mkl_rt', 'pthread']
library_dirs = ['/anaconda3/lib']
define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
include_dirs = ['/anaconda3/include']
lapack_opt_info:
libraries = ['mkl_rt', 'pthread']
library_dirs = ['/anaconda3/lib']
define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)]
include_dirs = ['/anaconda3/include']
- 创建一个长度为10的空向量
Z=np.zeros(10)
print (Z)
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
- 如何找到任何一个数组的内存大小?
Z=np.zeros((10,10))
print ("%d bytes" %(Z.size*Z.itemsize))
800 bytes
- 如何从命令行得到numpy中add函数的说明文档?
np.info(np.add)
add(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])
Add arguments element-wise.
Parameters
----------
x1, x2 : array_like
The arrays to be added. If ``x1.shape != x2.shape``, they must be
broadcastable to a common shape (which may be the shape of one or
the other).
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or `None`,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
Values of True indicate to calculate the ufunc at that position, values
of False indicate to leave the value in the output alone.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.
Returns
-------
add : ndarray or scalar
The sum of `x1` and `x2`, element-wise.
This is a scalar if both `x1` and `x2` are scalars.
Notes
-----
Equivalent to `x1` + `x2` in terms of array broadcasting.
Examples
--------
>>> np.add(1.0, 4.0)
5.0
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> np.add(x1, x2)
array([[ 0., 2., 4.],
[ 3., 5., 7.],
[ 6., 8., 10.]])
- 创建一个长度为10并且除了第五个值为1的空向量 (
Z = np.zeros(10)
Z[4] = 1#array[n]
print(Z)
[0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]
- 创建一个值域范围从10到49的向量
z=np.arange(10,50)
print (z)
[10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49]
- 反转一个向量(第一个元素变为最后一个
z=np.arange(10,50)
a=z[::-1]
print (a)
[49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26
25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10]
- 创建一个 3x3 并且值从0到8的矩阵
z=np.arange(9).reshape(3,3)
print (z)
[[0 1 2]
[3 4 5]
[6 7 8]]
- 找到数组[1,2,0,0,4,0]中非0元素的位置索引
nz=np.nonzero([1,2,0,0,4,0])#nonzero找出非零元素的索引
print (nz)
(array([0, 1, 4]),)
- 创建一个 3x3 的单位矩阵
n=np.eye(3,3)
print (n)
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
- 创建一个 3x3x3的随机数组
z=np.random.random((3,3,3))
print (z)
[[[0.38555942 0.03967291 0.11691279]
[0.14450181 0.84619474 0.96687301]
[0.84301805 0.32825705 0.91466083]]
[[0.62835269 0.1170878 0.54229367]
[0.87376554 0.41814426 0.76473372]
[0.18220092 0.61691598 0.58157413]]
[[0.60500251 0.55338976 0.19846201]
[0.95039281 0.7587364 0.51526201]
[0.710684 0.33470073 0.38118964]]]
- 创建一个 10x10 的随机数组并找到它的最大值和最小值
z=np.random.random((10,10))
print (z.min(),z.max())
0.015826515392604934 0.9991998936904795
- 创建一个长度为30的随机向量并找到它的平均值
z=np.random.random(30)
m=z.mean()
print (m)
0.47166627486012536
- 创建一个二维数组,其中边界值为1,其余值为0
z=np.zeros((10,10))
z[0,0]=1
print (z)
[[1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]
- 对于一个存在在数组,如何添加一个用0填充的边界?
Z = np.ones((5,5))
Z = np.pad(Z, pad_width=1, mode='constant', constant_values=0)
print(Z)
[[0. 0. 0. 0. 0. 0. 0.]
[0. 1. 1. 1. 1. 1. 0.]
[0. 1. 1. 1. 1. 1. 0.]
[0. 1. 1. 1. 1. 1. 0.]
[0. 1. 1. 1. 1. 1. 0.]
[0. 1. 1. 1. 1. 1. 0.]
[0. 0. 0. 0. 0. 0. 0.]]
- 以下表达式运行的结果分别是什么?
0 * np.nan
np.nan == np.nan
np.inf > np.nan
np.nan - np.nan
0.3 == 3 * 0.1
print(0 * np.nan)
print(np.nan == np.nan)
print(np.inf > np.nan)
print(np.nan - np.nan)
print(0.3 == 3 * 0.1)
nan
False
False
nan
False
- 创建一个 5x5的矩阵,并设置值1,2,3,4落在其对角线下方位置
Z = np.diag(1+np.arange(4),k=-1)
print(Z)
[[0 0 0 0 0]
[1 0 0 0 0]
[0 2 0 0 0]
[0 0 3 0 0]
[0 0 0 4 0]]
- 创建一个8x8 的矩阵,并且设置成棋盘样式
Z= np.zeros((8,8),dtype=int)
Z[1::2,::2] = 1
Z[::2,1::2] = 1
print(Z)
[[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]]
- 考虑一个 (6,7,8) 形状的数组,其第100个元素的索引(x,y,z)是什么?
print(np.unravel_index(100,(6,7,8)))
(1, 5, 4)
- 用tile函数去创建一个 8x8的棋盘样式矩阵
Z = np.tile( np.array([[0,1],[1,0]]), (4,4))
print(Z)
[[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]]
- 对一个5x5的随机矩阵做归一化(
Z=np.random.random((5,5))
Zmax, Zmin = Z.max(), Z.min()
Z = (Z - Zmin)/(Zmax - Zmin)
print(Z)
[[0.74508682 0.84287482 0.1859993 0.06004321 0.44425714]
[0.87338063 0.83313772 0.20199379 0.7457589 0. ]
[0.0014185 0.08812273 0.580381 0.10571226 0.22586788]
[0.16629494 1. 0.9870222 0.65151962 0.35522912]
[0.41009054 0.06744681 0.71881958 0.64453821 0.78537701]]
- 创建一个将颜色描述为(RGBA)四个无符号字节的自定义dtype?
color = np.dtype([("r", np.ubyte, 1),
("g", np.ubyte, 1),
("b", np.ubyte, 1),
("a", np.ubyte, 1)])
print (color)
[('r', 'u1'), ('g', 'u1'), ('b', 'u1'), ('a', 'u1')]
- 一个5x3的矩阵与一个3x2的矩阵相乘,实矩阵乘积是什么?
Z = np.dot(np.ones((5,3)), np.ones((3,2)))
print(Z)
[[3. 3.]
[3. 3.]
[3. 3.]
[3. 3.]
[3. 3.]]
- 给定一个一维数组,对其在3到8之间的所有元素取反
Z = np.arange(11)
Z[(3 < Z) & (Z <= 8)] *= -1
print(Z)
[ 0 1 2 3 -4 -5 -6 -7 -8 9 10]
- 下面脚本运行后的结果是什么?
print(sum(range(5),-1))
from numpy import *
print(sum(range(5),-1))
9
10
- 考虑一个整数向量Z,下列表达合法的是哪个?
Z = np.arange(5)
print (Z ** Z)
[ 1 1 4 27 256]
Z = np.arange(5)
2 << Z >> 2
array([0, 1, 2, 4, 8])
Z = np.arange(5)
Z<- Z
array([False, False, False, False, False])
Z = np.arange(5)
print(1j*Z)
[0.+0.j 0.+1.j 0.+2.j 0.+3.j 0.+4.j]
Z = np.arange(5)
print (Z/1/1)
[0. 1. 2. 3. 4.]
Z = np.arange(5)
print (Z<Z>Z)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-53-6fe7bb905724> in <module>
1 Z = np.arange(5)
----> 2 print (Z<Z>Z)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
- 下列表达式的结果分别是什么?
print(np.array(0) / np.array(0))
print(np.array(0) // np.array(0))
print(np.array([np.nan]).astype(int).astype(float))
nan
0
[-9.22337204e+18]
/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:1: RuntimeWarning: invalid value encountered in true_divide
"""Entry point for launching an IPython kernel.
/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:2: RuntimeWarning: divide by zero encountered in floor_divide
- 如何从零位对浮点数组做舍入 ?
Z = np.random.uniform(-10,+10,10)
print (np.copysign(np.ceil(np.abs(Z)), Z))
[ 5. 5. 1. 3. -8. 3. -7. -10. -5. -9.]
- 如何找到两个数组中的共同元素?
Z1 = np.random.randint(0,10,10)
Z2 = np.random.randint(0,10,10)
print(np.intersect1d(Z1,Z2))
[1 2 5 9]
- 如何忽略所有的 numpy 警告(尽管不建议这么做)?
# Suicide mode on
defaults = np.seterr(all="ignore")
Z = np.ones(1) / 0
# Back to sanity
_ = np.seterr(**defaults)
#An equivalent way, with a context manager:
with np.errstate(divide='ignore'):
Z = np.ones(1) / 0
- 下面的表达式是正确的吗?
np.sqrt(-1) == np.emath.sqrt(-1)
/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:1: RuntimeWarning: invalid value encountered in sqrt
"""Entry point for launching an IPython kernel.
False
- 如何得到昨天,今天,明天的日期?
yesterday = np.datetime64('today', 'D') - np.timedelta64(1, 'D')
today = np.datetime64('today', 'D')
tomorrow = np.datetime64('today', 'D') + np.timedelta64(1, 'D')
print ("Yesterday is " + str(yesterday))
print ("Today is " + str(today))
print ("Tomorrow is "+ str(tomorrow))
Yesterday is 2019-08-07
Today is 2019-08-08
Tomorrow is 2019-08-09
- 如何得到所有与2016年7月对应的日期?
Z = np.arange('2016-07', '2016-08', dtype='datetime64[D]')
print(Z)
['2016-07-01' '2016-07-02' '2016-07-03' '2016-07-04' '2016-07-05'
'2016-07-06' '2016-07-07' '2016-07-08' '2016-07-09' '2016-07-10'
'2016-07-11' '2016-07-12' '2016-07-13' '2016-07-14' '2016-07-15'
'2016-07-16' '2016-07-17' '2016-07-18' '2016-07-19' '2016-07-20'
'2016-07-21' '2016-07-22' '2016-07-23' '2016-07-24' '2016-07-25'
'2016-07-26' '2016-07-27' '2016-07-28' '2016-07-29' '2016-07-30'
'2016-07-31']
- 如何直接在位计算(A+B)*(-A/2)(不建立副本)?
A = np.ones(3)*1
B = np.ones(3)*2
C = np.ones(3)*3
np.add(A,B,out=B)
np.divide(A,2,out=A)
np.negative(A,out=A)
np.multiply(A,B,out=A)
array([-1.5, -1.5, -1.5])
- 用五种不同的方法去提取一个随机数组的整数部分
Z = np.random.uniform(0,10,10)
print (Z - Z%1)
[6. 2. 9. 4. 5. 8. 3. 2. 8. 5.]
print (np.floor(Z))
[6. 2. 9. 4. 5. 8. 3. 2. 8. 5.]
print (np.ceil(Z)-1)
[6. 2. 9. 4. 5. 8. 3. 2. 8. 5.]
print (Z.astype(int))
[6 2 9 4 5 8 3 2 8 5]
print (np.trunc(Z))
[6. 2. 9. 4. 5. 8. 3. 2. 8. 5.]
- 创建一个5x5的矩阵,其中每行的数值范围从0到4
Z = np.zeros((5,5))
Z += np.arange(5)
print (Z)
[[0. 1. 2. 3. 4.]
[0. 1. 2. 3. 4.]
[0. 1. 2. 3. 4.]
[0. 1. 2. 3. 4.]
[0. 1. 2. 3. 4.]]
- 通过考虑一个可生成10个整数的函数,来构建一个数组
def generate():
for x in range(10):
yield x
Z = np.fromiter(generate(),dtype=float,count=-1)
print (Z)
[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
- 创建一个长度为10的随机向量,其值域范围从0到1,但是不包括0和1
Z = np.linspace(0,1,11,endpoint=False)[1:]
print (Z)
[0.09090909 0.18181818 0.27272727 0.36363636 0.45454545 0.54545455
0.63636364 0.72727273 0.81818182 0.90909091]
- 创建一个长度为10的随机向量,并将其排序
Z = np.random.random(10)
Z.sort()
print (Z)
[0.0496976 0.07872811 0.10793056 0.12255355 0.22486103 0.29686983
0.59329425 0.73421228 0.88783313 0.93545901]
41.对于一个小数组,如何用比 np.sum更快的方式对其求和?
Z = np.arange(10)
np.add.reduce(Z)
45
- 对于两个随机数组A和B,检查它们是否相等
A = np.random.randint(0,2,5)
B = np.random.randint(0,2,5)
# Assuming identical shape of the arrays and a tolerance for the comparison of values
equal = np.allclose(A,B)
print(equal)
True
# 方法2
# Checking both the shape and the element values, no tolerance (values have to be exactly equal)
equal = np.array_equal(A,B)
print(equal)
True
- 创建一个只读数组(read-only)
Z = np.zeros(10)
Z.flags.writeable = False
Z[0] = 1
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-85-dcc5e7f145b5> in <module>
1 Z = np.zeros(10)
2 Z.flags.writeable = False
----> 3 Z[0] = 1
ValueError: assignment destination is read-only
- 将笛卡尔坐标下的一个10x2的矩阵转换为极坐标形式
Z = np.random.random((10,2))
X,Y = Z[:,0], Z[:,1]
R = np.sqrt(X**2+Y**2)
T = np.arctan2(Y,X)
print (R)
print (T)
[0.65956863 0.68083616 1.20479838 1.23784688 0.8774552 0.92096122
0.65240125 1.09372788 0.88872711 0.96581591]
[0.86651378 0.13042249 0.62051457 0.92737585 0.23950173 0.04312579
0.00595974 1.02267996 1.47012179 0.68205426]
- 创建一个长度为10的向量,并将向量中最大值替换为1
Z = np.random.random(10)
Z[Z.argmin()] = 0
print (Z)
[0.9312751 0.92070444 0. 0.25359596 0.82226417 0.71364516
0.23449391 0.92633386 0.9147423 0.46979603]
- 创建一个结构化数组,并实现 x 和 y 坐标覆盖 [0,1]x[0,1] 区域
Z = np.zeros((5,5), [('x',float),('y',float)])
Z['x'], Z['y'] = np.meshgrid(np.linspace(0,1,5),
np.linspace(0,1,5))
print(Z)
[[(0. , 0. ) (0.25, 0. ) (0.5 , 0. ) (0.75, 0. ) (1. , 0. )]
[(0. , 0.25) (0.25, 0.25) (0.5 , 0.25) (0.75, 0.25) (1. , 0.25)]
[(0. , 0.5 ) (0.25, 0.5 ) (0.5 , 0.5 ) (0.75, 0.5 ) (1. , 0.5 )]
[(0. , 0.75) (0.25, 0.75) (0.5 , 0.75) (0.75, 0.75) (1. , 0.75)]
[(0. , 1. ) (0.25, 1. ) (0.5 , 1. ) (0.75, 1. ) (1. , 1. )]]
- 给定两个数组X和Y,构造Cauchy矩阵C (Cij =1/(xi - yj))
X = np.arange(8)
Y = X + 0.5
C = 1.0 / np.subtract.outer(X, Y)
print(np.linalg.det(C))
3638.1636371179666
- 打印每个numpy标量类型的最小值和最大值?
for dtype in [np.int8, np.int32, np.int64]:
print(np.iinfo(dtype).min)
print(np.iinfo(dtype).max)
for dtype in [np.float32, np.float64]:
print(np.finfo(dtype).min)
print(np.finfo(dtype).max)
print(np.finfo(dtype).eps)
-128
127
-2147483648
2147483647
-9223372036854775808
9223372036854775807
-3.4028235e+38
3.4028235e+38
1.1920929e-07
-1.7976931348623157e+308
1.7976931348623157e+308
2.220446049250313e-16
- 如何打印一个数组中的所有数值?
np.set_printoptions(threshold=np.nan)
Z = np.zeros((16,16))
print (Z)
[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]
- 给定标量时,如何找到数组中最接近标量的值?
Z = np.arange(100)
v = np.random.uniform(0,100)
index = (np.abs(Z-v)).argmin()
print (Z[index])
33
版权声明:本文为qq_39303320原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。