How to copy a dictionary in python ?

To copy a dictionary in python, there are several approaches with different properties: [TOC] ### Copy a dictionary with deepcopy To get a copy completely independent of the first dictionary a solution is to use the function [deepcopy](https://docs.python.org/2/library/copy.html) >>> import copy >>> d1 = {'a':1} >>> d2 = copy.deepcopy(d1) >>> d2 {'a': 1} Here if the second dictionary d2 is modified the first dictionary will be not affected, examples:

Comment remplacer une colonne d'un tableau par la colonne d'un autre tableau en python ?

Exemples de comment remplacer (copier) une colonne d'un tableau par la colonne d'un autre tableau en python: [TOC] ### Tableau de même taille Cas ou les deux tableaux ont la même taille: exemple remplacer la colonne 1 du tableau N par la colonne 2 du tableau M: >>> import numpy as np >>> M = np.array([[2,7,1],[3,3,1],[5,4,2],[0,1,8]]) >>> M array([[2, 7, 1], [3, 3, 1], [5, 4, 2], [0, 1, 8]]) >>> N = np.zeros((4,6)) >>>

How to copy a list in python ?

To copy a list in python, a solution is to use the "built-in" function [list()](https://docs.python.org/2/library/functions.html#list), example: >>> L1 = ['a','b','c','d','e','f'] >>> L2 = list(L1) >>> L2 ['a', 'b', 'c', 'd', 'e', 'f'] Another solution is to use the list comprehension: >>> L1 = ['a','b','c','d','e','f'] >>> L2 = [i for i in L1] >>> L2 ['a', 'b', 'c', 'd', 'e', 'f'] **WARNING**: to copy a list do not use the = operator, because

Comment tester localement son microphone avec javascript et chrome ?

Un exemple de comment tester localement son microphone avec javascript et chrome: [TOC] L'objectif de départ était de pourvoir tester localement une application basée sur javascript utilisant le microphone pour reconnaitre du texte a partir de la voix (speech recognition). Le problème est qu'il n'est pas possible d'utiliser localement son microphone avec chrome directement, car il faut utiliser le https pour pouvoir utiliser le microphone. On va presenter ici une solution pour pouvoir test

How to get the size of a list in python ?

To get the size of a list in python, a solution is to use the python function [len](https://docs.python.org/2/library/functions.html#len), examples: >>> a = ['bob','ben','Tim'] >>> len(a) 3 another example with an empty list: >>> l = [] >>> len(l) 0 Another solution is to iterate in the list using a loop: >>> a = ['bob','ben','Tim'] >>> list_size = 0 >>> for i in a: ... list_size = list_size + 1 ... >>> list_size 3

How to find the smallest value in a list and its index with python ?

To find the smallest value in a list with python, a solution is to use the function [min()](https://www.tutorialspoint.com/python/list_min.htm): >>> l = [4,7,1,4,1,6,9] >>> min(l) 1 which returns 1 here. To find the index, there is the function [index()](https://www.tutorialspoint.com/python/list_index.htm), example: >>> l.index(min(l)) 2 Note: this function only returns the first index found. To find all the indexes of the smallest value (if there is several o

How to find the largest value in a list and its index with python ?

To find the largest number in a list with python, a solution is to use the function [max()](https://www.tutorialspoint.com/python/list_max.htm): >>> l = [4,7,9,4,1,6,9] >>> max(l) 9 which returns 9 here. To find the index, there is the function [index()](https://www.tutorialspoint.com/python/list_index.htm), example: >>> l.index(max(l)) 2 Note: this function only returns the first index found. To find all the indexes of a maximum value (if there is several occu

How to sort a list by the number of occurrences in python ?

Examples of how to sort a list by the number of occurrences (repetitions) in python [TOC] ### Sort a list of numbers by the number of occurrences: To sort a list of numbers by the number of occurrences, a solution is to use the function [counter](https://docs.python.org/2/library/collections.html#collections.Counter), example: >>> from collections import Counter >>> l = [8, 3, 9, 2, 7, 1, 3, 2, 0, 0, 7, 8, 6, 9, 4, 6, 3, 3, 2, 5] >>> l_sorted = Counter(l).most_common()

Trier une liste en fonction du nombre de répétitions (occurrences) avec python

Exemples de comment trier une liste en fonction du nombre de répétitions (occurrences) avec python [TOC] ### Trier une liste de nombres en fonction du nombre de répétitions Pour trier une liste de nombres en fonction du nombre de répétitions on peut utiliser la fonction [counter](https://docs.python.org/2/library/collections.html#collections.Counter), exemple: >>> from collections import Counter >>> l = [8, 3, 9, 2, 7, 1, 3, 2, 0, 0, 7, 8, 6, 9, 4, 6, 3, 3, 2, 5] >>>

How to find the element of a list with the maximum of repetitions (occurrences) in python ?

To find he element of a list with the maximum of repetitions (occurrences) in python, a solution is to use the function [counter](https://docs.python.org/2/library/collections.html#collections.Counter) from the python module collections, example: [TOC] ### Find the element of a list with the maximum of repetitions for a list of numbers Example with a list of numbers: >>> from collections import Counter >>> l = [8, 3, 9, 2, 7, 1, 3, 2, 0, 0, 7, 8, 6, 9, 4, 6, 3, 3, 2, 5]

How to convert a base64 image in png format using python ?

Example of how to convert a base64 image in png format using python (the input file base64.txt used in the following example can be found [here](https://www.science-emergence.com/Files/base64/)): import base64 from PIL import Image from io import BytesIO f = open('base64.txt', 'r') data = f.read() f.closed im = Image.open(BytesIO(base64.b64decode(data))) im.save('image.png', 'PNG') returns: [image:550 size:50 caption:How to save a base64 image in png format using pyt

How to convert a string into a list in python ?

Examples of how to convert a string in a list in python: [TOC] ### Change a string representation of a list into a list To convert a string representation of a list into a list in python, a solution is to use [ast.literal_eval](https://docs.python.org/3/library/ast.html), illustration: >>> s = '[1,2,3,4]' >>> type(s) <class 'str'> >>> import ast >>> l = ast.literal_eval(s) >>> type(l) <class 'list'> >>> l[1] 2 ### Put all string elements into a list: Example o

How to plot a point or a line in front of a imshow figure in matplotlib ?

Examples of how to plot a point or a line in front of a imshow figure in matplotlib [TOC] ### Superimpose a point and imshow Goal: find and plot a point corresponding to a global minima [images:draw-on-image-00;draw-on-image-01 dim:1*2 size:100 caption:How to plot a point or a line in front of a imshow figure in matplotlib ?] import numpy as np import matplotlib.pyplot as plt def f(x,y): return (x+y)*np.exp(-5.0*(x**2+y**2)) x,y = np.mgrid[-1:1:100j, -1:1:100j]

How to change colorbar labels in matplotlib ?

Examples of how to change colorbar labels in matplotlib: [TOC] ### Simple Colorbar with colorbar Plot a simple colorbar with matplotlib: [image:583 size:50 caption:How to change colorbar labels in matplotlib ?] import numpy as np import matplotlib.pyplot as plt def f(x,y): return (x+y)*np.exp(-5.0*(x**2+y**2)) x,y = np.mgrid[-1:1:100j, -1:1:100j] z = f(x,y) plt.imshow(z,extent=[-1,1,-1,1]) plt.colorbar() plt.savefig("ImshowColorBar01.png") plt.sh

How to put the colorbar below the figure in matplotlib ?

Example of how to put the colorbar below the figure in matplotlib [TOC] ### Horizontal colorbar in matplotlib To put the colorbar horizontal and below the figure a solution is to use the argument orientation = "horizontal" in the matplotlib function matplotlib.pyplot.colorbar(): [images:colorbar-positioning-01;colorbar-positioning-02 dim:1*2 size:100 caption:How to put the colorbar below the figure in matplotlib ?] #!/usr/bin/env python import matplotlib.pyplot as plt impor

How to have the colorbar with same size as the figure in matpltolib ?

Examples of how to adjust the size of a colorbar with the figure in matplotlib [TOC] ### Colorbar same size as the figure in matplotlib Example with a simple vertical colorbar: [image:446 size:50 caption:How to match the colorbar size with the figure size in matpltolib ?] import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable import numpy as np fig = plt.figure(1, figsize=(5, 3)) im = plt.imshow(np.arange(200).reshape((10,20)))

How to plot a simple bar chart with matplotlib ?

Examples of how to plot a simple bar chart using matplotlib and the function [bar](http://matplotlib.org/api/pyplot_api.html). [TOC] ### Plot a simple bar char with matplotlib [image:493 size:50 caption:How to plot a simple bar chart with matplotlib ?] import matplotlib.pyplot as plt import numpy as np fig = plt.figure() x = [1,2,3,4,5,6,7,8,9,10] height = [8,12,8,5,4,3,2,1,0,0] width = 1.0 plt.bar(x, height, width, color='b' ) plt.savefig('SimpleBar.png')

How to create and plot a simple histogram with matplotlib and python ?

Example of how to create and plot a simple histogram with matplotlib and python from a dataset: [TOC] ### Plot a simple histogram using matplotlib A simple histogram can be created with matplotlib using the function [hist()](http://matplotlib.org/1.3.1/api/pyplot_api.html#matplotlib.pyplot.hist), example: Note: see for example [Histograms vs. Bar Charts](https://www.edrawsoft.com/histogram-vs-bar-chart.php) to understand the differences between the 2 plots. [image:522 size:50 capt

How to add two lists together in python ?

Examples of how to merge two lists in python: [TOC] ### Merging two lists in python using the + operator >>> l1 = [1,2,3] >>> l2 = [4,5,6] >>> l3 = l1 + l2 >>> l3 [1, 2, 3, 4, 5, 6] another example: >>> l1 = [1,2,3] >>> l2 = [4,5,6] >>> l3 = l2 + l1 >>> l3 [4, 5, 6, 1, 2, 3] ### Combining two lists using zip If the goal is to iterate over two lists, a solution is to use [zip](https://docs.python.org/2/library/functions.html#zip

How to round the elements of a float array in python ?

To round the elements of a float array in python, a solution is to use the numpy function [around](http://docs.scipy.org/doc/numpy/reference/generated/numpy.around.html#numpy.around), example: >>> import numpy as np >>> A = np.array((0.4, 1.6, 2.1, -0.7, 0.9)) >>> np.around(A) array([ 0., 2., 2., -1., 1.]) It is also possible to define the number of decimals: >>> A = np.array((0.04, 1.06, 2.1, -0.7, 0.09)) >>> np.around(A, decimals=1) array([ 0.

How to convert a float array to an integer array in python ?

Examples of how to convert a float array to an integer array in python: [TOC] ### Using the numpy function astype To convert a float array to an integer array in python, a solution is to use [astype](https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.ndarray.astype.html), example: >>> import numpy as np >>> A = np.array((0.4, 1.6, 2.1, -3.7, 2.9)) >>> A array([ 0.4, 1.6, 2.1, -3.7, 2.9]) >>> A = A.astype(int) >>> A array([ 0, 1, 2

Comment convertir les éléments d'une matrice en entier avec numpy de python ?

Exemples de comment convertir les éléments d'une matrice en entier avec python: [TOC] ### Avec la fonction nympy astype Pour convertir les éléments d'une matrice en entier avec python, il existe la fonction numpy [astype](https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.ndarray.astype.html), exemple: >>> import numpy as np >>> A = np.array((0.4, 1.6, 2.1, -3.7, 2.9)) >>> A array([ 0.4, 1.6, 2.1, -3.7, 2.9]) >>> A = A.astype(int) >>> A

How to round a number in python ?

Examples of how to round a number in python: [TOC] ### Round a float number To round a number in python, a solution is to use the function [round](https://docs.python.org/2/library/functions.html) : >>> round(3.1415) 3 ### Round a float number (keep 1 digit after the decimal point) >>> x = 1.4567 >>> round(x,1) 1.5 ### Round a float number (keep 2 digits after the decimal point) >>> x = 1.4567 >>> round(x,2) 1.46 ### Change a float

How to save the figure color bar only in matplotlib ?

Example of how to save the figure color bar only in matplotlib (by Andras Deak from [Save colorbar for scatter plot separately](https://stackoverflow.com/questions/40813148/save-colorbar-for-scatter-plot-separately)) import matplotlib.pyplot as plt import numpy as np def f(x,y): return (x+y)*np.exp(-5.0*(x**2+y**2)) X,Y = np.mgrid[-1:1:100j, -1:1:100j] Z = f(X,Y) plt.figure() mpb = plt.pcolormesh(X,Y,Z,cmap='viridis') plt.title('How to save the colorbar separartly

Sauvegarder uniquement l'échelle de couleur d'une figure avec matplotlib

Exemple de comment sauvegarder uniquement l'échelle de couleur d'une figure avec matplotlib (d'apres Andras Deak: [Save colorbar for scatter plot separately](https://stackoverflow.com/questions/40813148/save-colorbar-for-scatter-plot-separately)) import matplotlib.pyplot as plt import numpy as np def f(x,y): return (x+y)*np.exp(-5.0*(x**2+y**2)) X,Y = np.mgrid[-1:1:100j, -1:1:100j] Z = f(X,Y) plt.figure() mpb = plt.pcolormesh(X,Y,Z,cmap='viridis') plt.title('How to