python 100_Numpy_exercises (2)

这是一篇关于Numpy的60道练习题目集合,涵盖了从基础操作到高级特性的各种问题,包括数组警告处理、数学运算、日期处理、数组创建、排序、比较、类型转换、矩阵运算等,旨在提升对Numpy库的掌握和理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

31. How to ignore all numpy warnings (not recommended)? (★☆☆)
# 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
32. Is the following expressions true? (★☆☆)
np.sqrt(-1) == np.emath.sqrt(-1)
import numpy as np
print (np.sqrt(-1))#实数
print (np.emath.sqrt(-1))#复数
nan
1j
D:\software\Anaconda\anaconda\lib\site-packages\ipykernel_launcher.py:2: RuntimeWarning: invalid value encountered in sqrt
33. How to get the dates of yesterday, today and tomorrow? (★☆☆)
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)
print (today)
print (tomorrow)
2019-03-06
2019-03-07
2019-03-09
34. How to get all the dates corresponding to the month of July 2016? (★★☆)
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']
35. How to compute ((A+B)*(-A/2)) in place (without copy)? (★★☆)
a = np.ones((3,3))
b = np.ones((3,3))*2
print (a)
print (b)
np.add(a,b,out = b)
# print (a)
print (b)
np.negative(np.divide(a,2,out = a),out = a)
np.multiply(b,a)
[[ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]]
[[ 2.  2.  2.]
 [ 2.  2.  2.]
 [ 2.  2.  2.]]
[[ 3.  3.  3.]
 [ 3.  3.  3.]
 [ 3.  3.  3.]]
array([[-1.5, -1.5, -1.5],
       [-1.5, -1.5, -1.5],
       [-1.5, -1.5, -1.5]])
import numpy as np
x1 = np.arange(9.0).reshape((3, 3))
print (x1)
x2 = np.arange(3.0)
print (x2)
np.add(x1, x2)
[[ 0.  1.  2.]
 [ 3.  4.  5.]
 [ 6.  7.  8.]]
[ 0.  1.  2.]
array([[  0.,   2.,   4.],
       [  3.,   5.,   7.],
       [  6.,   8.,  10.]])
import numpy as np
np.info(np.add)
add(x1, x2[, out])

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).

Returns
-------
add : ndarray or scalar
    The sum of `x1` and `x2`, element-wise.  Returns 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.]])
36. Extract the integer part of a random array using 5 different methods (★★☆)
import numpy as np
a = np.random.uniform(1,10,3)
print (a)
b = a-a%1
print (b)
[ 5.68428275  6.46149097  1.74833976]
[ 5.  6.  1.]
import numpy as np
a = np.random.uniform(1,10,3)
print (a)
b = np.ceil(a)-1
print (b)
[ 5.73062958  4.83969552  2.19314448]
[ 5.  4.  2.]
import numpy as np
a = np.random.uniform(1,10,3)
print (a)
b = np.floor(a)
print (b)
[ 9.71114723  5.91123853  1.34266563]
[ 9.  5.  1.]
import numpy as np
a = np.random.uniform(1,10,3)
print (a)
b = a.astype(int)
print (b)
[ 4.57905255  6.74753994  8.26644833]
[4 6 8]
import numpy as np
a = np.random.uniform(1,10,3)
print (a)
b = np.trunc(a)
print (b)
[ 4.04213929  2.44154839  2.88524378]
[ 4.  2.  2.]
np.info(np.trunc)
trunc(x[, out])

Return the truncated value of the input, element-wise.

The truncated value of the scalar `x` is the nearest integer `i` which
is closer to zero than `x` is. In short, the fractional part of the
signed number `x` is discarded.

Parameters
----------
x : array_like
    Input data.

Returns
-------
y : ndarray or scalar
    The truncated value of each element in `x`.

See Also
--------
ceil, floor, rint

Notes
-----
.. versionadded:: 1.3.0

Examples
--------
>>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])
>>> np.trunc(a)
array([-1., -1., -0.,  0.,  1.,  1.,  2.])
37. Create a 5x5 matrix with row values ranging from 0 to 4 (★★☆)
a = np.random.uniform(0,4,(5,5))
print (a)
[[ 3.68059573  2.89217004  3.93373932  1.89988404  3.31816657]
 [ 3.12213533  0.07068453  0.18528237  1.6167759   0.82046869]
 [ 0.37539813  1.50022606  3.3097724   2.90741528  0.01809809]
 [ 3.70381829  0.75977331  1.75437137  1.53818723  3.51736614]
 [ 1.40856755  0.92131058  3.86188851  0.8925987   3.67647075]]
a = np.zeros((5,5))
a += range (0,5)
print (a)
[[ 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.]]
38. Consider a generator function that generates 10 integers and use it to build an array (★☆☆)
def func():
    for i in range(10):
        yield i
   
a = np.fromiter(func(),dtype=float, count=-1)
print(a)
[ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9.]
 np.info(np.fromiter)
fromiter(iterable, dtype, count=-1)

Create a new 1-dimensional array from an iterable object.

Parameters
----------
iterable : iterable object
    An iterable object providing data for the array.
dtype : data-type
    The data-type of the returned array.
count : int, optional
    The number of items to read from *iterable*.  The default is -1,
    which means all data is read.

Returns
-------
out : ndarray
    The output array.

Notes
-----
Specify `count` to improve performance.  It allows ``fromiter`` to
pre-allocate the output array, instead of resizing it on demand.

Examples
--------
>>> iterable = (x*x for x in range(5))
>>> np.fromiter(iterable, np.float)
array([  0.,   1.,   4.,   9.,  16.])
39. Create a vector of size 10 with values ranging from 0 to 1, both excluded (★★☆)
np.info(np.linspace)
 linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)

Return evenly spaced numbers over a specified interval.

Returns `num` evenly spaced samples, calculated over the
interval [`start`, `stop`].

The endpoint of the interval can optionally be excluded.

Parameters
----------
start : scalar
    The starting value of the sequence.
stop : scalar
    The end value of the sequence, unless `endpoint` is set to False.
    In that case, the sequence consists of all but the last of ``num + 1``
    evenly spaced samples, so that `stop` is excluded.  Note that the step
    size changes when `endpoint` is False.
num : int, optional
    Number of samples to generate. Default is 50. Must be non-negative.
endpoint : bool, optional
    If True, `stop` is the last sample. Otherwise, it is not included.
    Default is True.
retstep : bool, optional
    If True, return (`samples`, `step`), where `step` is the spacing
    between samples.
dtype : dtype, optional
    The type of the output array.  If `dtype` is not given, infer the data
    type from the other input arguments.

    .. versionadded:: 1.9.0

Returns
-------
samples : ndarray
    There are `num` equally spaced samples in the closed interval
    ``[start, stop]`` or the half-open interval ``[start, stop)``
    (depending on whether `endpoint` is True or False).
step : float, optional
    Only returned if `retstep` is True

    Size of spacing between samples.


See Also
--------
arange : Similar to `linspace`, but uses a step size (instead of the
         number of samples).
logspace : Samples uniformly distributed in log space.

Examples
--------
>>> np.linspace(2.0, 3.0, num=5)
array([ 2.  ,  2.25,  2.5 ,  2.75,  3.  ])
>>> np.linspace(2.0, 3.0, num=5, endpoint=False)
array([ 2. ,  2.2,  2.4,  2.6,  2.8])
>>> np.linspace(2.0, 3.0, num=5, retstep=True)
(array([ 2.  ,  2.25,  2.5 ,  2.75,  3.  ]), 0.25)

Graphical illustration:

>>> import matplotlib.pyplot as plt
>>> N = 8
>>> y = np.zeros(N)
>>> x1 = np.linspace(0, 10, N, endpoint=True)
>>> x2 = np.linspace(0, 10, N, endpoint=False)
>>> plt.plot(x1, y, 'o')
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.plot(x2, y + 0.5, 'o')
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.ylim([-0.5, 1])
(-0.5, 1)
>>> plt.show()
a = np.linspace(0,1,num=11,endpoint=False)[1:]
print (a)
[ 0.09090909  0.18181818  0.27272727  0.36363636  0.45454545  0.54545455
  0.63636364  0.72727273  0.81818182  0.90909091]
40. Create a random vector of size 10 and sort it (★★☆)
a = np.random.rand(10)
print (a)
print (sorted(a))
print (a)
[ 0.12869995  0.97825072  0.06260481  0.10932202  0.40136214  0.9808369
  0.22498057  0.02908049  0.73547941  0.56994736]
[0.029080487074700012, 0.062604806619652731, 0.10932202350502584, 0.12869994535209672, 0.22498057120505621, 0.40136214089195832, 0.56994736490402698, 0.73547940896389297, 0.97825072255312717, 0.98083689547423358]
[ 0.12869995  0.97825072  0.06260481  0.10932202  0.40136214  0.9808369
  0.22498057  0.02908049  0.73547941  0.56994736]
import numpy as np
b = np
### 回答1: 100 numpy exercises是一份以PythonNumPy为主题的练习题集合。NumPyPython中最常用的数值计算库之一,它提供了高效的数组操作和向量化计算功能。这份练习题集的目的是帮助学习者更好地理解和掌握NumPy的各种功能和用法。 这份题集包含了100个不同的练习题,分为易、中、难三个难度级别。每个练习题都有明确的目标,例如创建特定的数组、对数组进行操作和计算,以及使用NumPy库中的各种函数和方法等。题集中的每个练习都带有详细的题目描述和示例代码,学习者可以通过阅读题目描述和参考示例代码来理解问题的背景和解决思路。 通过完成这份练习题集,学习者可以提升自己在NumPy库的应用能力,深入了解NumPy的各种功能和用法。同时,通过实践解决不同难度的问题,学习者还可以提高自己的编程能力和解决问题的思维能力。 对于想要学习NumPy库的人来说,这份练习题集是一份很好的学习资源。学习者可以逐个尝试解决每个练习题,并在解题过程中不断探索和学习NumPy库的各种功能和技巧。完成这份练习题集后,学习者将会对NumPy库有更深入的理解,并能够灵活应用NumPy库解决实际问题。 总之,100 numpy exercises提供了一系列以NumPy库为主题的练习题,帮助学习者提升自己在NumPy库的应用能力,深入理解NumPy库的各种功能和用法,同时也能提高编程和问题解决能力。这份练习题集对于想要学习NumPy的人来说,是一份很好的学习资源。 ### 回答2: 《100 NumPy练习题》(中文版)是一本关于NumPy库的练习题集。NumPy是一个功能强大的开源数学库,它提供了高性能的多维数组对象和用于处理这些数组的工具。 这本练习题集共包含100个通过NumPy库实现的练习题,旨在帮助读者提升对NumPy的理解和应用能力。这些练习题涵盖了NumPy库的各个方面,包括数组的创建、索引和切片、数组的运算和处理、数组的变形和操作等内容。 这本练习题集的特点如下: 1. 简洁明了:每个练习题都包含了问题描述和具体要求,读者可以根据需求在代码中填充相应的代码,然后运行并查看结果。 2. 渐进难度:练习题的难度是逐渐增加的,从简单的问题逐步过渡到复杂的问题,帮助读者逐步提升技能。 3. 具体实例:练习题中提供了许多具体实例,通过实际的应用场景帮助读者理解NumPy库的用法。 4. 答案解析:每个练习题附有详细的答案解析,读者可以通过对比自己的答案来检查和理解问题的解决思路。 通过完成这些练习题,读者可以巩固NumPy的基础知识,并掌握更高级和复杂的用法。这对于希望深入学习数据分析、科学计算和机器学习领域的读者来说,是一本很好的参考书。 总之,《100 NumPy练习题》(中文版)是一本适合各个层次的读者学习NumPy库的练习题集,它将帮助读者提升对NumPy库的理解和应用能力,是学习NumPy的一本很好的参考书籍。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值