numpy 100题

原网址:https://github.com/rougier/numpy-100/blob/master/100%20Numpy%20exercises.md

# 100 numpy exercise
# 题目来源于 https://github.com/rougier/numpy-100/blob/master/100%20Numpy%20exercises.md

# 1. 导入numpy包并命名为np
import numpy as np

# 2. 打印numpy的版本和配置
print(np.__version__)
np.show_config()

# 3. 建立一个长度为10的向量
Z = np.zeros(10)
print(Z)

# 4. 怎样去查看一个数组的内存大小
Z = np.zeros([10, 10])
print("%d bytes" % (Z.size * Z.itemsize))

# 5. 怎样从命令行中获得numpy的add函数
# %run `python -c "import numpy; numpy.info(numpy.add)"`

# 6. 建立一个长度为10的除了第五位为1其他全为0的向量
Z = np.zeros(10)
Z[4] = 1
print(Z)

# 7. 建立一个值从10到49的向量
Z = np.arange(10, 50)
print(Z)

# 8. 反转一个向量(使最后一位到第一位)
Z = np.arange(10, 50)
Z = Z[::-1]
print(Z)

# 9. 建立一个3*3的矩阵,值从0到8
Z = np.arange(0, 9).reshape(3, 3)
print(Z)

# 10. 找到一个数组中非0元素的index
nz = np.nonzero([1,2,0,0,4,0])
print(nz)

# 11. 建立一个3*3的对角矩阵
Z = np.eye(3)
print(Z)

# 12. 建立一个3*3*3的随机数数组
Z = np.random.random((3, 3, 3))
print(Z)

# 13. 建立一个10*10的随机数组,找到数组中的最大值和最小值
Z = np.random.random((3, 3))
Z_max, Z_min = Z.max(), Z.min()
print(Z_max, Z_min)

# 14. 建立一个长度为30的随机向量,并打印出向量的平均值
Z = np.random.random(30)
Z_mean = Z.mean()
print(Z_mean)

# 15. 建立一个二维数组使周边为1中心为0
Z = np.ones((10,10))
Z[1:-1, 1:-1] = 0
print(Z)

# 16. 将一个全1的数组四周增加0
Z = np.ones((10, 10))
Z = np.pad(Z, pad_width=1, mode='constant', constant_values=0)
print(Z)

# 17. 下面运行结果是什么
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)

# 18. 建立一个5*5的矩阵,并让对角线下的值为1,2,3,4
Z = np.diag(1+np.arange(4), k=-1)
print(Z)

# 19. 建立一个8*8的0和1间隔的矩阵
Z = np.zeros((8, 8), dtype=int)
#Z[1::2, ::2] = 1
Z[::2, 1::2] = 1
print(Z)

# 20. 意思是返回一个flatten矩阵的第100个元素的index的横竖索引(x,y,z)
print(np.unravel_index(100, (6, 7, 8)))

# 21. 使用tile方法建立一个8*8的0和1间隔的矩阵
print(np.tile(np.array([[0,1], [1,0]]), (4, 4)))

# 22. 标准化一个5*5的随机矩阵
Z = np.random.random((5, 5))
Z_mean, Z_max, Z_min = Z.mean(), Z.max(), Z.min()
Z = (Z - Z_min) / (Z_max - Z_min)
print(Z)

# 23. 建立一个客户dtype用4bytes(RGBA)来描述一种颜色
color = np.dtype([("r", np.ubyte, 1),
                  ("g", np.ubyte, 1),
                  ("b", np.ubyte, 1),
                  ("a", np.byte, 1)])

# 24. 5*3的矩阵与3*2的矩阵做product
Z = np.dot(np.ones((5, 3)), np.ones((3, 2)))
print(Z)
# another function
Z = np.ones((5, 3)) @ np.ones((3, 2))
print(Z)

# 25. 将一个一维的数组中元素在3-8之间的元素转换为负数
Z = np.arange(1, 10)
Z[(Z >= 3) & (Z <= 8)] *= -1
print(Z)

# 26. 下面的代码的运行结果分别为什么
print(sum(range(5), -1))
from numpy import *
print(sum(range(5), -1))

# 27. 对于一个整数向量Z,下面哪一个表达式是合法的
#不合法
Z**Z
#合法
2 << Z >> 2
#合法
Z <- Z
#合法
1j*Z
#合法
Z/1/1
#不合法
Z<Z>Z

# 28.下面表达式的结果是什么
# " / "就一定表示 浮点数除法,返回浮点结果;" // "表示整数除法
print(np.array(0) / np.array(0))
print(np.array(0) // np.array(0))
print(np.array([np.nan]).astype(int).astype(float))

# 29. 如果将一个浮点数数组做四舍五入
Z = np.random.uniform(-10, 10, 10)
print(np.copysign(np.ceil(np.abs(Z)), Z))

# 30. 找到两个数组中的相同的值
Z1 = np.random.randint(0, 10, 10)
Z2 = np.random.randint(0, 10, 10)
print(np.intersect1d(Z1, Z2))

# 31. 怎样去忽视所有的numpy的警告
defaults = np.seterr(all = "ignore")
Z = np.ones(1) / 0
_ = np.seterr(**defaults)

# 32. 下面的表达式是否正确
np.sqrt(-1) == np.emath.sqrt(-1)

# 33. 怎样去得到昨天,今天和明天的日期
yesterday = np.datetime64('today', 'D') - np.timedelta64(1, 'D')
today = np.datetime64('today', 'D')
tomorrow = np.datetime64('today', 'D') + np.timedelta64(1, 'D')

# 34. 怎样获得2016年7月所有的日期
Z = np.arange('2016-07', '2016-08', dtype='datetime64[D]')
print(Z)

# 35. 怎样在计算((A+B)*(-A/2))
A = np.ones(3) * 1
B = np.ones(3) * 2
np.add(A, B, out=B)
np.divide(A, 2, out=A)
np.negative(A, out=A)
np.multiply(A, B, out=A)

# 36. 使用5种不同的方法从一个随机数组种提取整数
Z = np.random.uniform(0, 10, 10)
print(Z - Z%1)
print(np.floor(Z))
print(np.ceil(Z)-1)
print(Z.astype(int))
print(np.trunc(Z))

# 37. 建立一个5*5的行的值从0-4的矩阵
Z = np.zeros((5, 5))
Z = Z + np.arange(5)
print(Z)

# 38. 考虑一个生成函数使其可以产生10个整数并能用这些整数建立一个数组
def generater():
    for i in range(10):
        yield i
Z = np.fromiter(generater(), dtype=float, count=-1)
print(Z)

# 39. 建立一个长度为10的向量,并使它的值从0到1(不包括0和1)
Z = np.linspace(0, 1, 11, endpoint=False)[1:]
print(Z)

# 40. 建立一个随机的长度为10的向量并且排序
Z = np.random.random(10)
Z.sort()
print(Z)

# 41. 怎样去求解一个小的数组的和比使用np.sum快呢
Z = np.arange(10)
print(np.add.reduce(Z))

# 42. 怎样判断两个随机矩阵A和B是否相等
A = np.random.randint(0, 2, 5)
B = np.random.randint(0, 2, 5)
#
equal = np.allclose(A, B)
print(equal)
#
equal = np.array_equal(A, B)
print(equal)

# 43. 使一个数组是不可移动的(只读)
Z = np.zeros(10)
Z.flags.writeable = False
Z[0] = 1

# 44. 考虑一个随机的10*2矩阵代表笛卡尔坐标系,转换它们到极坐标系
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, T)

# 45. 建立一个长度为10的随机向量并将最大值替换为0
Z = np.random.random(10)
Z[Z.argmax()] = 0
print(Z)

# 46. Create a structured array with x and y coordinates covering the [0,1]x[0,1] area
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)

# 47. 将两个数组X,和Y,建立柯西矩阵C(Cij =1/(xi - yj))
# 这里,我们输入X为:[0, 1, 2, 3, 4, 5, 6, 7], 输入Y为:[0.5  1.5  2.5  3.5  4.5  5.5  6.5  7.5
#], np.substract.outer做的运算为
# [0-0,5, 0-1.5, 0-2.5, ..., 0-7.5]
# [1-0.5, 1-1.5, 1-2.5, ..., 1-7.5]
# ...
# [7-0.5, 7-1.5, 7-2.5, ..., 7-7.5]
X = np.arange(8)
Y = X + 0.5
C = 1.0 / np.subtract.outer(X, Y)
print(np.linalg.det(C))

# 48. 打印出每一个numpy scalar type的最小和最大的代表值
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)

# 49. 怎样打印一个数组中所有的值
np.set_printoptions(threshold=np.nan)
Z = np.zeros((16, 16))
print(Z)

# 50. 怎样去找到一个向量中最近的值
Z = np.arange(100)
V = np.random.uniform(0, 100)
index = (np.abs(Z-V)).argmin()
print(index)

# 51. 建立一个结构数组表示一个位置(x, y)和一种颜色(r, g, b)
Z = np.zeros(10, [('position', [('x', float, 1),
                                ('y', float, 1)]),
                  ('color', [('r', float, 1),
                             ('g', float, 1),
                             ('b', float, 1)])

])
print(Z)

# 52. 从一个(100, 2)的随机向量中计算点到点之间的距离
# 52. Consider a random vector with shape (100,2) representing coordinates, find point by point distances
Z = np.random.random((10,2))
X,Y = np.atleast_2d(Z[:,0], Z[:,1])
D = np.sqrt( (X-X.T)**2 + (Y-Y.T)**2)
print(D)

# Much faster with scipy
import scipy
# Thanks Gavin Heverly-Coulson (#issue 1)
import scipy.spatial

Z = np.random.random((10,2))
D = scipy.spatial.distance.cdist(Z,Z)
print(D)

# 53. 怎样将一个32bits的浮点型转换成一个32bits的整型
Z = np.arange(10, dtype=np.float32)
Z = Z.astype(np.int32, copy=False)
print(Z)

# 54. 怎样去读取下面的文件
from io import StringIO

# Fake file
s = StringIO("""1, 2, 3, 4, 5\n
                6,  ,  , 7, 8\n
                 ,  , 9,10,11\n""")
Z = np.genfromtxt(s, delimiter=",", dtype=np.int)
print(Z)

# 55. 什么是numpy数组的相等的枚举
# What is the equivalent of enumerate for numpy arrays?
Z = np.arange(9).reshape(3, 3)
# ndenumerate返回数组的下标(x, y)
for index, value in np.ndenumerate(Z):
    print(index, value)

for index in np.ndindex(Z.shape):
    print(index, Z[index])

# 56. 生成一个二维的高斯数组
X, Y = np.meshgrid(np.linspace(-1, 1, 10), np.linspace(-1, 1, 10))
D = np.sqrt(X*X+Y*Y)
sigma, mu = 1.0, 0.0
G = np.exp(-((D-mu)**2 / (2.0 * sigma**2)))
print(G)

# 57. 怎样在二维数组中随机放置p个元素
n = 10
p = 3
Z = np.zeros((n, n))
np.put(Z, np.random.choice(range(n*n), p, replace=False), 25)
print(Z)

# 58. 减去矩阵每一行的平均值
# 58. Subtract the mean of each row of a matrix
X = np.random.rand(5, 10)

# Recent versions of numpy
Y = X - X.mean(axis=1, keepdims=True)

# Older versions of numpy
Y = X - X.mean(axis=1).reshape(-1, 1)

print(Y)

# 59. 怎样去根据第n列对一个数组排序
Z = np.random.randint(1, 10, (3, 3))
print(Z)
Z = Z[Z[:, 0].argsort()]
print(Z)

# 60.怎样判断一个2D的数组里面有空的列
Z = np.random.randint(0, 3, (3, 10))
print(Z)
print((~Z.any(axis=1)).any())

# 61. 从一个给定的数组中找到一个最近的值
# np.abs(Z-z).argmin()算出来的是数组中最近元素的下标,Z.flat[]可以查找出数组中的这个下标对应的元素
Z = np.random.uniform(0, 1, 10)
z = 0.5
m = Z.flat[np.abs(Z-z).argmin()]

# 62. 怎样用iterator去计算两个(1,3)和(3,1)数组的和
# Considering two arrays with shape (1,3) and (3,1), how to compute their sum using an iterator?
A = np.arange(3).reshape(3, 1)
B = np.arange(3).reshape(1, 3)
it = np.nditer([A, B, None])
for x, y, z in it:
    z[...] = x + y
print(it.operands[2])

# 63. 建立一个有列名的数组类
class NamedArray(np.ndarray):
    def __new__(cls, array, name="no name"):
        obj = np.asarray(array).view(cls)
        obj.name = name
        return obj
    def __array_finalize__(self, obj):
        if obj is None: return
        self.info = getattr(obj, 'name', "no name")

Z = NamedArray(np.arange(10), "range_10")
print(Z.name)

猜你喜欢

转载自blog.csdn.net/katherine_hsr/article/details/79297913