0% found this document useful (0 votes)
11 views15 pages

Cours Numpy

This document discusses NumPy arrays and operations. It introduces how to define arrays using NumPy functions like np.array(), np.zeros(), and np.ones(). It covers array properties like size, shape, and dtype. It also demonstrates indexing, slicing, modifying values, concatenating arrays, and performing mathematical operations on arrays.

Uploaded by

m.shaggyspringer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views15 pages

Cours Numpy

This document discusses NumPy arrays and operations. It introduces how to define arrays using NumPy functions like np.array(), np.zeros(), and np.ones(). It covers array properties like size, shape, and dtype. It also demonstrates indexing, slicing, modifying values, concatenating arrays, and performing mathematical operations on arrays.

Uploaded by

m.shaggyspringer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

10/12/23, 7:37 PM Cours_numpy - Jupyter Notebook

In [ ]:  # pip install numpy

In [ ]:  ​

In [1]:  import numpy as np

1. define arrays (vecteurs et matrices)


In [79]:  A = np.array([1, 2, 3]) # générateur par défaut, qui permet de convertir des listes (ou autres objets) en tableau
B = np.zeros((2, 3)) # tableau de 0 aux dimensions 2x3
C = np.ones((2, 3)) # tableau de 1 aux dimensions 2x3

print(A); print('\n')
print(B); print('\n')
print(C); print('\n')

[1 2 3]

[[0. 0. 0.]
[0. 0. 0.]]

[[1. 1. 1.]
[1. 1. 1.]]

In [80]:  np.full((2,2), 659)

Out[80]: array([[659, 659],


[659, 659]])

localhost:8888/notebooks/séance 3/Cours_numpy.ipynb 1/15


10/12/23, 7:37 PM Cours_numpy - Jupyter Notebook

In [81]:  np.full_like(B, 4)

Out[81]: array([[4., 4., 4.],


[4., 4., 4.]])

In [85]:  # Repeat an array


r1 = np.repeat([A], 3, axis=0)
print(r1)

[[1 2 3]
[1 2 3]
[1 2 3]]

In [1]:  import numpy as np

In [2]:  A = np.linspace(1, 10, 10)



print(A);

[ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.]

Pas comme les listes:

numpy arrays ne peuvent contenir qu'un seul type

In [10]:  import numpy as np



mixed_array = np.array([1, "apple", 3.14])

print(mixed_array)

['1' 'apple' '3.14']

In [12]:  mixed_array.dtype

Out[12]: dtype('<U32')

localhost:8888/notebooks/séance 3/Cours_numpy.ipynb 2/15


10/12/23, 7:37 PM Cours_numpy - Jupyter Notebook

2. size, dim, shape


In [23]:  A = np.zeros((2, 3)) # création d'un tableau de shape (2, 3)
A

Out[23]: array([[0., 0., 0.],


[0., 0., 0.]])

In [24]:  A.size

Out[24]: 6

In [26]:  A.ndim

Out[26]: 2

In [25]:  A.shape

Out[25]: (2, 3)

3. indexing
In [1]:  import numpy as np

a = np.array([[1,2,3,4,5,6,7],
[8,9,10,11,12,13,14]])
print(a)

[[ 1 2 3 4 5 6 7]
[ 8 9 10 11 12 13 14]]

In [2]:  a[1][1]

Out[2]: 9

localhost:8888/notebooks/séance 3/Cours_numpy.ipynb 3/15


10/12/23, 7:37 PM Cours_numpy - Jupyter Notebook

In [3]:  # Get a specific element [r, c]


a[1][5] #or a[1, 5]

Out[3]: 13

In [5]:  a

Out[5]: array([[ 1, 2, 3, 4, 5, 6, 7],


[ 8, 9, 10, 11, 12, 13, 14]])

In [6]:  a[-1] #dernière ligne

Out[6]: array([ 8, 9, 10, 11, 12, 13, 14])

In [8]:  a[-1][-1] #dernière ligne #dernière colonne

Out[8]: 14

In [9]:  a

Out[9]: array([[ 1, 2, 3, 4, 5, 6, 7],


[ 8, 9, 10, 11, 12, 13, 14]])

In [11]:  a[0, 2 : len(a[0]): 2] # a[ligne, start : end : steps]

Out[11]: array([3, 5, 7])

In [12]:  a

Out[12]: array([[ 1, 2, 3, 4, 5, 6, 7],


[ 8, 9, 10, 11, 12, 13, 14]])

In [13]:  a[1,5] = 20 #modifier la valeur dans la ligne 1 (deuxième ligne) et la colonne 5 (6ème col)
a

Out[13]: array([[ 1, 2, 3, 4, 5, 6, 7],


[ 8, 9, 10, 11, 12, 20, 14]])

localhost:8888/notebooks/séance 3/Cours_numpy.ipynb 4/15


10/12/23, 7:37 PM Cours_numpy - Jupyter Notebook

In [15]:  a[: , 2] = [1,2] #modifier la colonne 2


a

Out[15]: array([[ 1, 2, 1, 4, 5, 6, 7],


[ 8, 9, 2, 11, 12, 20, 14]])

4. special functions
In [24]:  A = np.zeros((2, 3)) # création d'un tableau de shape (2, 3)
A

Out[24]: array([[0., 0., 0.],


[0., 0., 0.]])

In [25]:  A = A.reshape((3, 2)) # redimensionne le tableau A (3 lignes, 2 colonnes)


A

Out[25]: array([[0., 0.],


[0., 0.],
[0., 0.]])

localhost:8888/notebooks/séance 3/Cours_numpy.ipynb 5/15


10/12/23, 7:37 PM Cours_numpy - Jupyter Notebook

In [42]:  A = np.zeros((2, 3))


B = np.ones((2, 3))

C = np.concatenate((A, B), axis=0) #concatener au niveau des lignes

print(A); print('\n')
print(B); print('\n')
print(C); print('\n')

[[0. 0. 0.]
[0. 0. 0.]]

[[1. 1. 1.]
[1. 1. 1.]]

[[0. 0. 0.]
[0. 0. 0.]
[1. 1. 1.]
[1. 1. 1.]]

localhost:8888/notebooks/séance 3/Cours_numpy.ipynb 6/15


10/12/23, 7:37 PM Cours_numpy - Jupyter Notebook

In [43]:  A = np.zeros((2, 3))


B = np.ones((2, 3))

C = np.concatenate((A, B), axis=1) #concatener au niveau des colonnes



print(A); print('\n')
print(B); print('\n')
print(C); print('\n')

[[0. 0. 0.]
[0. 0. 0.]]

[[1. 1. 1.]
[1. 1. 1.]]

[[0. 0. 0. 1. 1. 1.]
[0. 0. 0. 1. 1. 1.]]

In [16]:  L = [1, 1, 1, 1, 3, 4, 5, 6, 6, 6, 6]

uniques, counts = np.unique(L, return_counts=True)

In [17]:  uniques

Out[17]: array([1, 3, 4, 5, 6])

In [18]:  counts

Out[18]: array([4, 1, 1, 1, 4], dtype=int64)

5. math operations (matrices)


all can be found here: https://numpy.org/doc/stable/reference/routines.math.html (https://numpy.org/doc/stable/reference/routines.math.html)

localhost:8888/notebooks/séance 3/Cours_numpy.ipynb 7/15


10/12/23, 7:37 PM Cours_numpy - Jupyter Notebook

In [19]:  a = np.array([1,2,3,4])
print(a)

[1 2 3 4]

In [20]:  a + 2

Out[20]: array([3, 4, 5, 6])

In [21]:  a - 2

Out[21]: array([-1, 0, 1, 2])

In [22]:  a * 2

Out[22]: array([2, 4, 6, 8])

In [23]:  a / 2

Out[23]: array([0.5, 1. , 1.5, 2. ])

In [24]:  # b = np.array([1,0,1,0,1]) #error


b = np.array([1,0,1,0])
a + b

Out[24]: array([2, 2, 4, 4])

In [25]:  a ** 2

Out[25]: array([ 1, 4, 9, 16])

In [26]:  np.cos(a)

Out[26]: array([ 0.54030231, -0.41614684, -0.9899925 , -0.65364362])

localhost:8888/notebooks/séance 3/Cours_numpy.ipynb 8/15


10/12/23, 7:37 PM Cours_numpy - Jupyter Notebook

In [27]:  np.sum(a)

Out[27]: 10

In [28]:  np.prod(a) #product of all elements

Out[28]: 24

In [29]:  np.cumsum(a)

Out[29]: array([ 1, 3, 6, 10])

In [30]:  np.cumprod(a)

Out[30]: array([ 1, 2, 6, 24])

In [31]:  np.diff(a) #2-1, 3-2, 4-3

Out[31]: array([1, 1, 1])

In [32]:  np.exp(a)

Out[32]: array([ 2.71828183, 7.3890561 , 20.08553692, 54.59815003])

In [33]:  np.log(a)

Out[33]: array([0. , 0.69314718, 1.09861229, 1.38629436])

In [34]:  np.log(np.exp(a))

Out[34]: array([1., 2., 3., 4.])

In [35]:  # --------------------------------------------------------------

localhost:8888/notebooks/séance 3/Cours_numpy.ipynb 9/15


10/12/23, 7:37 PM Cours_numpy - Jupyter Notebook

In [36]:  a = np.array([1,2,3,4])
b = np.array([2,4,6,8])

In [37]:  print(a)

[1 2 3 4]

In [38]:  print(b)

[2 4 6 8]

In [39]:  print(a.shape)
print(b.shape)

(4,)
(4,)

In [40]:  np.add(a, b)

Out[40]: array([ 3, 6, 9, 12])

In [41]:  np.subtract(a, b)

Out[41]: array([-1, -2, -3, -4])

7. Matrix multiplication options:


1. np.multiply(a,b) ----------- + sum ----------- or a * b +sum
2. np.dot(a,b)
3. np.matmul(a, b) ----------- or @

localhost:8888/notebooks/séance 3/Cours_numpy.ipynb 10/15


10/12/23, 7:37 PM Cours_numpy - Jupyter Notebook

1. for 1D arrays

In [44]:  a = np.array([1,2,3,4])
b = np.array([2,4,6,8])

In [45]:  a

Out[45]: array([1, 2, 3, 4])

In [46]:  b

Out[46]: array([2, 4, 6, 8])

In [47]:  np.multiply(a,b) #+ sum or a * b +sum

Out[47]: array([ 2, 8, 18, 32])

In [48]:  1*2 , 2*4 , 3*6 , 4*8

Out[48]: (2, 8, 18, 32)

In [49]:  np.dot(a, b)

Out[49]: 60

In [50]:  np.matmul(a, b)
# a@b

Out[50]: 60

In [51]:  1*2 + 2*4 + 3*6 + 4*8

Out[51]: 60

localhost:8888/notebooks/séance 3/Cours_numpy.ipynb 11/15


10/12/23, 7:37 PM Cours_numpy - Jupyter Notebook

2. for 2D arrays and more

In [52]:  c = np.array([[1, 2, 3],


[4, 5, 6]])
c.shape

Out[52]: (2, 3)

In [53]:  d = np.array([[6, 2, 1],


[8, 9, 7]])
d.shape

Out[53]: (2, 3)

In [54]:  np.multiply(c,d) #element wise

Out[54]: array([[ 6, 4, 3],


[32, 45, 42]])

In [55]:  np.matmul(c, d) #error

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[55], line 1
----> 1 np.matmul(c, d) #error

ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->
(n?,m?) (size 2 is different from 3)

localhost:8888/notebooks/séance 3/Cours_numpy.ipynb 12/15


10/12/23, 7:37 PM Cours_numpy - Jupyter Notebook

In [56]:  np.dot(c, d) #error

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[56], line 1
----> 1 np.dot(c, d) #error

File <__array_function__ internals>:200, in dot(*args, **kwargs)

ValueError: shapes (2,3) and (2,3) not aligned: 3 (dim 1) != 2 (dim 0)

In [57]:  d

Out[57]: array([[6, 2, 1],


[8, 9, 7]])

In [58]:  dt = d.T #Transposed or reshape


dt

Out[58]: array([[6, 8],


[2, 9],
[1, 7]])

In [59]:  dr = d.reshape(3,2) #not like transposed !! but works


dr

Out[59]: array([[6, 2],


[1, 8],
[9, 7]])

In [60]:  np.dot(c, dt)

Out[60]: array([[ 13, 47],


[ 40, 119]])

localhost:8888/notebooks/séance 3/Cours_numpy.ipynb 13/15


10/12/23, 7:37 PM Cours_numpy - Jupyter Notebook

In [61]:  np.matmul(c, dt)

Out[61]: array([[ 13, 47],


[ 40, 119]])

In [62]:  np.dot(c, dr)

Out[62]: array([[35, 39],


[83, 90]])

7. read and write txt files


In [66]:  # 1. load text file

f = np.loadtxt('test.txt')
f

Out[66]: array([1., 2., 3., 4., 5., 6.])

In [67]:  f.shape

Out[67]: (6,)

In [68]:  # 2. modify

f[0] = 999
f

Out[68]: array([999., 2., 3., 4., 5., 6.])

In [69]:  # 3. save

np.savetxt('test3.txt', f, fmt='%d') #delimiter=',')

localhost:8888/notebooks/séance 3/Cours_numpy.ipynb 14/15


10/12/23, 7:37 PM Cours_numpy - Jupyter Notebook

In [ ]:  ​

localhost:8888/notebooks/séance 3/Cours_numpy.ipynb 15/15

You might also like