Python_Numpy100题下

Python_Numpy100题下

参考: https://github.com/rougier/numpy-100

Python_Numpy100题上

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)表示坐标的随机向量,逐点计算距离(★★☆)

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.如何将浮点(32位)数组就地转换为整数(32位)?

# Thanks Vikas (https://stackoverflow.com/a/10622758/5989906)
# & unutbu (https://stackoverflow.com/a/4396247/5989906)
Z = (np.random.rand(10)*100).astype(np.float32)
print(Z)
Y = Z.view(np.int32)
print(Y)
Y[:] = Z
print(Y)

在这里插入图片描述

54.如何读取以下文件(★★☆)

from io import StringIO

# Fake file
s = StringIO('''1, 2, 3, 4, 5

                6,  ,  , 7, 8

                 ,  , 9,10,11
''')
Z = np.genfromtxt(s, delimiter=",", dtype=np.int)
print(Z)

在这里插入图片描述

55.numpy数组的枚举等价于什么(★★☆)

Z = np.arange(9).reshape(3,3)
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元素(★★☆)

# Author: Divakar

n = 10
p = 3
Z = np.zeros((n,n))
np.put(Z, np.random.choice(range(n*n), p, replace=False),1)
print(Z)

在这里插入图片描述

58.减去矩阵每行的平均值(★★☆)

# Author: Warren Weckesser

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列对数组排序(★★☆)

# Author: Steve Tjoa

Z = np.random.randint(0,10,(3,3))
print(Z)
print(Z[Z[:,2].argsort()])

在这里插入图片描述

60.如何判断给定的2D数组是否有空列(★★☆)

# Author: Warren Weckesser

Z = np.random.randint(0,3,(3,10))
print(Z)
print((~Z.any(axis=0)).any())

在这里插入图片描述

61.从数组中给定的值中找出最近的值(★★☆)

Z = np.random.uniform(0,1,10)
print(Z)
z = 0.5
m = Z.flat[np.abs(Z - z).argmin()]
print(m)

在这里插入图片描述

62.考虑形状为(1,3)和(3,1)的两个数组,如何使用迭代器计算它们的和(★★☆)

A = np.arange(3).reshape(3,1)
print(A)
B = np.arange(3).reshape(1,3)
print(B)
it = np.nditer([A,B,None])
for x,y,z in it: z[...] = x + y
print(it.operands[2])

在这里插入图片描述

63.创建一个具有name属性的数组类(★★☆)

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)
print(Z)

在这里插入图片描述

64.考虑一个给定的向量,如何给第二个向量索引的每个元素加1(注意重复索引)(★★★)

Z = np.ones(10)
I = np.random.randint(0,len(Z),20)
print(I)
Z += np.bincount(I, minlength=len(Z))
print(Z)

# Another solution
# Author: Bartosz Telenczuk
np.add.at(Z, I, 1)
print(Z)

在这里插入图片描述

65.如何基于索引列表(I)将向量(X)的元素累加到数组(F)中(★★★)

# Author: Alan G Isaac

X = [1,2,3,4,5,6]
I = [1,3,9,3,4,1]
F = np.bincount(I,X)
print(F)

在这里插入图片描述
在这里插入图片描述
参考:numpy.bincount详解

66.考虑(dtype=ubyte)的(w,h,3)图像,计算唯一颜色的数量(★★☆)

# Author: Fisher Wang

w, h = 256, 256
I = np.random.randint(0, 4, (h, w, 3)).astype(np.ubyte)
colors = np.unique(I.reshape(-1, 3), axis=0)
#print(colors)
n = len(colors)
print(n)

# Faster version
# Author: Mark Setchell
# https://stackoverflow.com/a/59671950/2836621

w, h = 256, 256
I = np.random.randint(0,4,(h,w,3), dtype=np.uint8)

# View each pixel as a single 24-bit integer, rather than three 8-bit bytes
I24 = np.dot(I.astype(np.uint32),[1,256,65536])

# Count unique colours
n = len(np.unique(I24))
print(n)

在这里插入图片描述

67.考虑到四维数组,如何一次得到最后两个轴的和(★★★)

A = np.random.randint(0,10,(3,4,3,4))
# solution by passing a tuple of axes (introduced in numpy 1.7.0)
sum = A.sum(axis=(-2,-1))
print(sum)
# solution by flattening the last two dimensions into one
# (useful for functions that don't accept tuples for axis argument)
sum = A.reshape(A.shape[:-2] + (-1,)).sum(axis=-1)
print(sum)

在这里插入图片描述

68.考虑到一维向量D,如何使用描述子集索引的相同大小的向量S来计算D的子集的平均值(★★★)

# Author: Jaime Fernández del Río

D = np.random.uniform(0,1,100)
S = np.random.randint(0,10,100)
D_sums = np.bincount(S, weights=D)
D_counts = np.bincount(S)
D_means = D_sums / D_counts
print(D_means)

# Pandas solution as a reference due to more intuitive code
import pandas as pd
print(pd.Series(D).groupby(S).mean())

在这里插入图片描述

69.如何得到点积的对角线(★★★)

# Author: Mathieu Blondel

A = np.random.uniform(0,1,(5,5))
B = np.random.uniform(0,1,(5,5))

# Slow version
print(np.diag(np.dot(A, B)))

# Fast version
print(np.sum(A * B.T, axis=1))

# Faster version
print(np.einsum("ij,ji->i", A, B))

在这里插入图片描述

70.考虑向量[1,2,3,4,5],如何建立一个新的向量,在每个值之间插入3个连续的零(★★★)

# Author: Warren Weckesser

Z = np.array([1,2,3,4,5])
nz = 3
Z0 = np.zeros(len(Z) + (len(Z)-1)*(nz))
Z0[::nz+1] = Z
print(Z0)

在这里插入图片描述

后面题都比较复杂并且不常用,不再更新!
后续代码:https://github.com/rougier/numpy-100/blob/master/100_Numpy_exercises_with_solutions.md

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值