Python

Introduction à Numpy

Numpy est une librairie Python qui introduit une nouvelle structure de données l’Array, qui est comme une liste, mais en beaucoup plus rapide.

Installation de Numpy

pip install numpy
#test.py
import numpy
arr = numpy.array([1,2,3,4,5])
print(arr)

Importation de Numpy avec un alias

import numpy as np
arr = np.array([1,2,3,4,5])
print(np.__version__)

Array scalaire 0 dimension

import numpy as np
arr = np.array(42)
print(arr) 

Array unidimensionnel

import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr) 

Array 2D

import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr) 

Dans le cas particuliers des matrices Numpy a une librairie dédiée numpy.mat

Array 3D utilisé pour représenter les tenseurs.

Checker la dimension d’un array avec ndim

import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.ndim) 

Index des array c’est comme les listes

Le notation est différente ce ce qu’on peut voir en Javascript

import numpy as np
arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
print('2nd element on 1st dim: ', arr[0, 1]) 

Index négatif

pour accéder depuis la fin

import numpy as np
arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
print('Last element from 2nd dim: ', arr[1, -1]) 

Array slicing

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[1:5]) 
print(arr[4:]) 
print(arr[:4]) 
print(arr[:]) 
print(arr[-3:-1]) #Array slicing négatif
print(arr[1:5:2]) #step slicing !cette notation exclut le dernier (tem index 5 n'est pas pris en compte)

Slicing 2D array

import numpy as np
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[1, 1:4])  # sur un array
print(arr[0:2, 2]) # sur deux array
print(arr[0:2, 1:4]) # sur deux array de 1 à 4

Les datatype de Numpy


		

Insérer un modèle dans la base avec Django

De la même façon qu’on peut générer un formulaire facilement avec le modèle, on peut facilement insérer dans la base de données une entité provenant d’un formulaire HTML généré de cette façon, ou en le construisant from scratch depuis une méthode de view

#models.py
class Foo(models.Model):
    name = models.CharField(max_length=100)

#view.py
def add(request):
    foo_instance = Foo.objects.create(name='test')
    return render(request, 'some_name.html.html')

Ou l’on peut se servir du model directement

from django.http import HttpResponse
from django.template import loader

from .models import Article


def index(request):
    article = Article()
    article.title = 'This is the title'
    article.contents = 'This is the content'
    article.save()

    template = loader.get_template('articles/index.html')
    context = {
        'new_article_id': article.pk,
    }
    return HttpResponse(template.render(context, request))

En utilisant les model form c’et plus simple

# views.py
def monform(request):
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = MyProductForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/products/thanks')

    # if a GET (or any other method) we'll create a blank form
    else:
        form = MyProductForm()

    return render(request, 'myproductform.html', {'form': form})

#form.py
class MyProductForm(ModelForm):
    class Meta:
        model = Product
        fields = ['name', 'price', 'stock', 'image']  #or use tuple
#models.py
class Product(models.Model):
    name = models.CharField(max_length=50)
    price = models.FloatField()
    stock = models.IntegerField()
    image = models.CharField(max_length=2000)
Retour en haut