Numpy 入门(三)Elementwise operations
本帖最后由 hj170520 于 2020-6-9 22:59 编辑入门代码(三)
# Numerical operations on arrays
```
%matplotlib inline
import matplotlib.pyplot as plt # the tidy way
import pandas as pd
import numpy as np
```
# 5. Elementwise operations
## Basic operations
### With scalars:
```
>> a = np.array()
>> a + 1
array()
>> 2**a
array([ 2,4,8, 16])
```
### All arithmetic operates elementwise:
```
>> b = np.ones(4) + 1
>> a - b
array([-1.,0.,1.,2.])
>> a * b
array()
```
### These operations are of course much faster than if you did them in pure python:
```
>> j = np.arange(5)
>> 2**(j + 1) - j
array([ 2,3,6, 13, 28])
>> a = np.arange(10000)
>> %timeit a + 1
3.25 μs ± 366 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
>> l = range(10000)
>> %timeit
592 μs ± 51.4 μs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
```
### Array multiplication is not matrix multiplication:
```
>> c = np.ones((3, 3))
>> c * c # NOT matrix multiplication!
array([,
,
])
```
### Matrix multiplication:
```
>> c.dot(c)
array([,
,
])
```
> Exercise: Elementwise operations
>
> Try simple arithmetic elementwise operations: add even elements with odd elements
> Time them against their pure python counterparts using %timeit.
> Generate:
a_j = 2^(3*j) - j
## Other operations
### Comparisons:
```
>> a = np.array()
>> b = np.array()
>> a == b
array()
>> a > b
array()
>> a = np.array()
>> b = np.array()
>> c = np.array()
>> np.array_equal(a, b)
False
>> np.array_equal(a, c)
True
```
### Logical operations:
```
>> a = np.array(, dtype=bool)
>> b = np.array(, dtype=bool)
>> np.logical_or(a, b)
array([ True,True,True, False])
>> np.logical_and(a, b)
array([ True, False, False, False])
```
### Transcendental functions:
```
>> a = np.arange(5)
>> np.sin(a)
array([ 0. ,0.84147098,0.90929743,0.14112001, -0.7568025 ])
>> np.log(a)
array([ -inf, 0. , 0.69314718, 1.09861229, 1.38629436])
>> np.exp(a)
array([ 1. ,2.71828183,7.3890561 , 20.08553692, 54.59815003])
```
### Shape mismatches
```
>> a = np.arange(4)
>> a + np.array()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (4) (2)
```
### Transposition:
```
>> a = np.triu(np.ones((3, 3)), 1) # see help(np.triu)
>> a
array([,
,
])
>> a.T
array([,
,
])
```
> Exercise other operations
>
> Look at the help for np.allclose. When might this be useful?
> Look at the help for np.triu and np.tril
>
爱了爱了,居然在这里也可以学习python 正在学习,感谢分享 多谢分享,我也学习下了
页:
[1]