numpy 100 题(1-60)

自己最近也在学,找了挺多资源,整合一起编了一下

jupyter里面编的,全部复制运行可能有点问题。

有问题一起讨论,我也在学,还有挺多不懂的。

这里是1-60题

#1. Import the numpy package under the name np (★☆☆)
import numpy as np

#2. Print the numpy version and the configuration (★☆☆)
np.__version__

np.show_config()

#3.Create a null vector of size 10 (★☆☆)
a = np.empty((2,10))

#1. Import the numpy package under the name np (★☆☆)
import numpy as np

#2. Print the numpy version and the configuration (★☆☆)
np.__version__

np.show_config()

#3.Create a null vector of size 10 (★☆☆)
a = np.empty((2,10))

a

np.size(a)

np.shape(a)

np.shape(a)[1]

#4. How to find the memory size of any array (★☆☆)
#获取内存大小
b = np.size(a)
c = a.itemsize
b*c

a.size

a.shape

a.dtype

#5. How to get the documentation of the numpy add function from the command line? (★☆☆)
#在np库中获取特定函数信息的方法
np.info(np.add)

#6. Create a null vector of size 10 but the fifth value which is 1 (★☆☆)
d = np.empty(10)
d[4] = 1
d

#7. Create a vector with values ranging from 10 to 49 (★☆☆)
e1 = np.array(range(10,50))

e2 = np.arange(10,50)
e2

#8. Reverse a vector (first element becomes last) (★☆☆)
e3 = a[::-1]
e3

#9. Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆)
np.arange(0,9).reshape(3,3)

#10. Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆)
f = np.array([1,2,0,0,4,0])
f1 = []
for num in f:
    if num != 0:
        f1.append(num)
f1

#11. Create a 3x3 identity matrix (★☆☆)
g = np.identity(3)

np.random.random_sample(g.shape)

np.random.rand(9).reshape(3,3)

np.info(np.random)

#12. Create a 3x3x3 array with random values (★☆☆)
#13. Create a 10x10 array with random values and find the minimum and maximum values
h = np.random.random(100).reshape(10,10)

np.max(h)

np.min(h)

#14. Create a random vector of size 30 and find the mean value (★☆☆)
i = np.random.random(30)

np.info(np.average)

np.average(i)

#15. Create a 2d array with 1 on the border and 0 inside (★☆☆)
j = np.ones((10,10))
j[1:-1,1:-1] = 0
j

#6. How to add a border (filled with 0's) around an existing array? (★☆☆)
np.pad(j,pad_width = 1, mode = 'constant',constant_values = 10)

#17. What is the result of the following expression? (★☆☆)
'''
0 * np.nan
np.nan == np.nan
np.inf > np.nan
np.nan - np.nan
np.nan in set([np.nan])
0.3 == 3 * 0.1
'''
0*np.nan

np.info(np.nan)

np.nan == np.nan

np.inf >np.nan
#np.nan不能进行比较

np.nan - np.nan
#nan参与运算必然是nan

np.nan in set([np.nan])
#set得到的是无序集合

0.3 == 3*0.1
#浮点数在计算机中储存为二进制,所以比较仍然存在问题

#18. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (★☆☆)
np.diag([1,2,3,4],1)

#19. Create a 8x8 matrix and fill it with a checkerboard pattern (★☆☆)
k = np.zeros((8,8))
k[1::2,::2] = 1
k[::2,1::2] = 1
k

#20. Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element?
np.unravel_index(99,(6,7,8))

#21. Create a checkerboard 8x8 matrix using the tile function (★☆☆)
np.tile([[0,1],[1,0]],(4,4))

#22. Normalize a 5x5 random matrix (★☆☆)
k-np.mean(k))/np.std(k)

#23 Create a custom dtype that describes a color as four unsigned bytes (RGBA) (★☆☆)
RGBA = np.dtype([("r", np.ubyte, 1),
                  ("g", np.ubyte, 1),
                  ("b", np.ubyte, 1),
                  ("a", np.ubyte, 1)])
RGBA

#24. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product) 
np.dot(np.ones((5,3)),np.ones((3,2)))

### np.array和np.mat的区别

#事实上是数组和矩阵的区别,数组取出一列还是一维的,但是矩阵中取出一列还是二维数组

#在运算方式上np.dot始终表示矩阵乘法,但是矩阵的点乘用np.multiply(),数组用*也可以

np.multiply(np.array([2,2]),np.array([[2],[2]]))

#25. Given a 1D array, negate all elements which are between 3 and 8, in place. (★☆☆)
l = np.array([1,2,3,4,5,6,7,8,9,10])
l1 = np.array([int(num) for num in l])
l2 = l1
l2[4:8] = (-1)*l2[4:8]
l2
l4 = np.random.randint(1,10,10)
l4[(3 <l4) & (l4 <= 8)] *= -1
l4

'''
26. What is the output of the following script? (★☆☆)
# Author: Jake VanderPlas

print(sum(range(5),-1))
from numpy import *
print(sum(range(5),-1))
'''
print(sum(range(5),-1))
from numpy import *
print(sum(range(5),0))
#该题目考查了python自带sum和numpy的np.sum的区别
#sum不能处理二维数组,只是对一维数据求和,
#np.sum则可以,其第二个参数指定按列(axis=0)
#或行(axis=1)求和,不设该参数是全部求和。

sum(range(5),-1)

'''
27. Consider an integer vector Z, which of these expressions are legal? (★☆☆)
Z**Z
2 << Z >> 2
Z <- Z
1j*Z
Z/1/1
Z<Z>Z
'''
z = np.random.randint(1,10,10)
z

z**z

2 << z >> 2

z <- z

1j*z

z/1/1

z<z>z

'''
28. What are the result of the following expressions?
np.array(0) / np.array(0)
np.array(0) // np.array(0)
np.array([np.nan]).astype(int).astype(float)
'''

#np.array(0) / np.array(0)
#np.array(0) // np.array(0)
np.array([np.nan]).astype(int).astype(float)

#29. How to round away from zero a float array ? (★☆☆)
#四舍五入保留两位小数
m = np.random.random(10)
np.around(m,2)

#30. How to find common values between two arrays? (★☆☆)
n1 = np.random.randint(1,10,10)
n2 = np.random.randint(1,10,10)
#np.info(np.intersect1d)
np.intersect1d(n1,n2)

print(n1)
print(n2)

31. How to ignore all numpy warnings (not recommended)? (★☆☆)
hint: np.seterr, np.errstate

32. Is the following expressions true? (★☆☆)
np.sqrt(-1) == np.emath.sqrt(-1)
hint: imaginary number

33. How to get the dates of yesterday, today and tomorrow? (★☆☆)
hint: np.datetime64, np.timedelta64

34. How to get all the dates corresponding to the month of July 2016? (★★☆)
hint: np.arange(dtype=datetime64['D'])

35. How to compute ((A+B)*(-A/2)) in place (without copy)? (★★☆)
hint: np.add(out=), np.negative(out=), np.multiply(out=), np.divide(out=)

36. Extract the integer part of a random array of positive numbers using 4 different methods (★★☆)
hint: %, np.floor, astype, np.trunc

37. Create a 5x5 matrix with row values ranging from 0 to 4 (★★☆)
hint: np.arange

38. Consider a generator function that generates 10 integers and use it to build an array (★☆☆)
hint: np.fromiter

39. Create a vector of size 10 with values ranging from 0 to 1, both excluded (★★☆)
hint: np.linspace

40. Create a random vector of size 10 and sort it (★★☆)
hint: sort

# 32. Is the following expressions true? (★☆☆)
a = np.emath.sqrt(-1)
b = np.sqrt(-1)
a == b

#33. How to get the dates of yesterday, today and tomorrow? (★☆☆)
print("today:{}".format(np.datetime64('today','D')))
print("yesterday:{}".format(np.datetime64('today','D')-np.timedelta64('1','D')))
print("tomorrow:{}".format(np.datetime64('today','D')+np.timedelta64('1','D')))

#34. How to get all the dates corresponding to the month of July 2016? (★★☆)
np.arange('20210301','20210310',dtype='datetime64[D]')

#35.How to compute ((A+B)*(-A/2)) in place (without copy)? (★★☆)
a = np.ones(3)
b = np.ones(3)*2
np.add(a,b,out = b)
np.negative(a,out = a)
np.multiply(a,b,out = b)
np.divide(b,2)

#36. Extract the integer part of a random array of positive numbers using 4 different methods (★★☆)
z = np.random.uniform(0,10,10)
z

z1 = np.around(z-0.5)
z1

z2 = z - z % 1
z2

z3 = np.floor(z)
z3

z4 = z.astype(int)
z4

z5 = np.trunc(z)
z5

#37. Create a 5x5 matrix with row values ranging from 0 to 4 (★★☆)
m = np.arange(0,5)
m1 = np.zeros((5,5))
m1 += m
m1

#38. Consider a generator function that generates 10 integers and use it to build an array (★☆☆)
def gen():
    for x in range(10):
        yield x
np.fromiter(gen(),dtype = int)

#不知道在干嘛

#39. Create a vector of size 10 with values ranging from 0 to 1, both excluded (★★☆)
#创建一个10维的向量,不包含0和1
np.linspace(0,1,num = 11,endpoint = False)[1:]
#np.linspace就是等间距地生成数组,endpoint就是包不包含右端点

#40. Create a random vector of size 10 and sort it (★★☆)
a = np.random.random(10)
np.sort(a,axis = 0)

import numpy as np
import time as time

#41. How to sum a small array faster than np.sum? (★★☆)
z = np.arange(10)
start1 = time.time()
result = np.sum(z)
end1 = time.time()
t1 = end1 - start1
print('运行时间1为{}'.format(t1),'结果1为{}'.format(result))
start2 = time.time()
result = np.add.reduce(z)
end2 = time.time()
t2 = end2 - start2
print('运行时间2为{}'.format(t1),'结果2为{}'.format(result))
t1 - t2 < 0

#42. Consider two random array A and B, check if they are equal (★★☆)
a = np.random.rand(2,3)
b = np.random.rand(2,3)
e1 = np.allclose(a,b)#在误差范围内,一般是10^(-5)
e2 = np.array_equal(a,b)
print(e1,e2)

#43. Make an array immutable (read-only) (★★☆)
z.flags.writeable = 0
z[0 ] = 1

#44. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (★★☆)
#将笛卡尔坐标转化为极坐标
#极坐标的转化
a = np.random.random((10,2))
x = a[:,0]
y = a[:,1]
rao = np.sqrt(x**2+y**2)
theta = np.arctan2(y,x)
polar = np.array([rao,theta])
polar

#45. Create random vector of size 10 and replace the maximum value by 0 (★★☆)
a = np.random.random(10)
print(a)
a[np.argmax(a)] = 0 
a

#46. Create a structured array with x and y coordinates covering the [0,1]x[0,1] area (★★☆)
z = np.zeros((3,3),[('x',float),('y',float)])
z['x'],z['y'] = np.meshgrid(np.linspace(0,1,3),np.linspace(0,1,3))
a = 1/(z['x']**2+1) + 3/(z['y']**2+1)
h = plt.contourf(z['x'],z['y'],a)
plt.show()

#计算网格上的函数
#np.meshgrid 是用来将坐标向量转化为坐标矩阵
import matplotlib.pyplot as plt
x = np.arange(-5, 5, 0.1)
y = np.arange(-5, 5, 0.1)
xx, yy = np.meshgrid(x, y, sparse=True)
z = np.sin(xx**2 + yy**2)/(xx**2 +yy**2)
h = plt.contourf(x,y,z)
plt.show()

#47. Given two arrays, X and Y, construct the Cauchy matrix C (Cij =1/(xi - yj))
x = np.linspace(1,10,10)
y = np.linspace(1,10,10)+0.1
c= 1/np.subtract.outer(x,y)
c

#48. Print the minimum and maximum representable value for each numpy scalar type (★★☆)
#输出不同数据类型的最大最小值和占据的空间
np.iinfo(np.int8).min
np.iinfo(np.int8).max
#finfo是输出float类型 iinfo是int类型
#np.int8/32/64
#np.float32/64
np.finfo(np.float64).eps

#49. How to print all the values of an array? (★★☆)
#np.set_printoptions(threshold = np.nan)
#有问题,无法设置,可以考虑maxsize
#defualt一般是1000

#50. How to find the closest value (to a given scalar) in a vector? (★★☆)
#找两个向量数值距离最近的量的位置
z = np.arange(100)
v = np.random.randint(0,100,100)
index = np.abs((z-v)).argmin()
index2 = np.abs((z-v)).argmax()
print(z[index],v[index],z[index2],v[index2])


51. Create a structured array representing a position (x,y) and a color (r,g,b) (★★☆)
hint: dtype

52. Consider a random vector with shape (100,2) representing coordinates, find point by point distances (★★☆)
hint: np.atleast_2d, T, np.sqrt

53. How to convert a float (32 bits) array into an integer (32 bits) in place?
hint: view and [:] =

54. How to read the following file? (★★☆)
1, 2, 3, 4, 5
6,  ,  , 7, 8
 ,  , 9,10,11
hint: np.genfromtxt

55. What is the equivalent of enumerate for numpy arrays? (★★☆)
hint: np.ndenumerate, np.ndindex

56. Generate a generic 2D Gaussian-like array (★★☆)
hint: np.meshgrid, np.exp

57. How to randomly place p elements in a 2D array? (★★☆)
hint: np.put, np.random.choice

58. Subtract the mean of each row of a matrix (★★☆)
hint: mean(axis=,keepdims=)

59. How to sort an array by the nth column? (★★☆)
hint: argsort

60. How to tell if a given 2D array has null columns? (★★☆)
hint: any, ~

import numpy as np

#51. Create a structured array representing a position (x,y) and a color (r,g,b) (★★☆)
z = np.zeros(5,[('position',[('x',float,1),('y',float,1)]),('color',[('r',float,1),('b',float,1),('g',float,1)])])
z
#就是和46用的方法一样,就是指定每个数据的具体是啥
z['position']['x'] = 1
z

#52. Consider a random vector with shape (100,2) representing coordinates, find point by point distances (★★☆)
z = np.random.randint(0,100,(10,2))
x,y = np.atleast_2d(z[:,0],z[:,0])
d = np.sqrt((x-x.T)**2 +(y-y.T)**2)
d
#X.T是转化成转置,其实就是计算向量的“相关矩阵”

#53. How to convert a float (32 bits) array into an integer (32 bits) in place?
z = np.random.rand(10)*10
z1 = np.array([int(num) for num in z])
print(z)
print(z1)

#54. How to read the following file? (★★☆)

data =  np.genfromtxt('try.txt',delimiter = ',',skip_header = 0)
data

#55. What is the equivalent of enumerate for numpy arrays? (★★☆)
#不知道在干嘛

#56. Generate a generic 2D Gaussian-like array (★★☆)
#生成二维类高斯阵
#通用方法
#生成正态分布的数据一般是
z = np.random.randn(4,4)
sigma, mu = 2.0,2.0
G = (z+mu)*sigma
G

#57. How to randomly place p elements in a 2D array? (★★☆)
#如何在一个二维数组里随机放p个元素
#没卵用

#58. Subtract the mean of each row of a matrix (★★☆)
g = np.random.randint(0,10,(2,2))
print(g)
g.mean(axis=1,keepdims=0)
#axis = 1 就是按照行来平均
# keepdims = 1 就是保留原来的矩阵形式

#59. How to sort an array by the nth column? (★★☆)

print(z)
z[z[:,1].argsort()]

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值