Numpy 入门(二)Copies and views & Fancy indexing
本帖最后由 hj170520 于 2020-6-9 10:19 编辑入门代码(二)
本文有计算prime numbers(素数)的讲解~
# 3. Copies and views
> np.may_share_memory() to check if two arrays share the same memory block.
```
>> a = np.arange(10)
>> a
array()
>> b = a[::2]
>> b
array()
>> np.may_share_memory(a, b) # <--
True
>> b = 12
>> b
array()
>> a # (!)
array()
```
```
>> a = np.arange(10)
>> c = a[::2].copy() # force a copy
>> c = 12
>> a
array()
>> np.may_share_memory(a, c)
False
```
### Compute prime numbers in 0–99, with a sieve
> Construct a shape (100,) boolean array is_prime, filled with True in the beginning:
```
>> is_prime = np.ones((100,), dtype=bool)
```
> Cross out 0 and 1 which are not primes:
```
>> is_prime[:2] = 0
```
> For each integer j starting from 2, cross out its higher multiples:
```
>> N_max = int(np.sqrt(len(is_prime) - 1))
>> for j in range(2, N_max + 1):
is_prime = False
>> np.nonzero(is_prime)
(array([ 2,3,5,7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59,
61, 67, 71, 73, 79, 83, 89, 97]),)
```
> Skim through help(np.nonzero), and print the prime numbers
> Follow-up:
> – Move the above code into a script file named prime_sieve.py – Run it to check it works
> – Use the optimization suggested in the sieve of Eratosthenes:
> 1. Skip j which are already known to not be primes
> 2. The first number to cross out is $𝑗^2$
# 4. Fancy indexing
### Using boolean masks
```
>> np.random.seed(3)
>> a = np.random.randint(0, 21, 15)
>> a
array()
```
```
>> (a % 3 == 0)
array([False,True, False,True, False, False, False,True, False,
True,True, False,True, False, False])
```
```
>> mask = (a % 3 == 0)
>> extract_from_a = a # or, a
>> extract_from_a # extract a sub-array with the mask
array([ 3,0,9,6,0, 12])
```
```
>> a = -1
>> a
array()
```
### Indexing with an array of integers
```
>> a = np.arange(0, 100, 10)
>> a
array([ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90])
```
```
>> a[]# note: it is a python list
array()
```
```
>> a[] = -100
>> a
array([ 0, 10, 20, 30, 40, 50, 60, -100, 80, -100])
```
> Tip: When a new array is created by indexing with an array of integers, the new array has the same shape as the array of integers:
```
>> a = np.arange(10)
>> idx = np.array([, ])
>> idx.shape
(2, 2)
```
```
>> a
array([,
])
```
The image below illustrates various fancy indexing applications {:301_971:} 我们这个论坛没有“jupyter notebook”的显示功能,所以我就都打出来了,希望各位见怪不怪~~{:301_996:}
都是码出来的,不容易啊 楼主辛苦
页:
[1]