The Open Science Project

Identification


Sign-Up


Create a new notebook

Contributors


Open Science Notebooks

Notes


How to create a data frame in python using pandas ?

Daidalos October 15, 2019

Creative Commons License

Examples of how to create a data frame using the python module pandas [TOC] ### Create a data frame using an array Import pandas and numpy: >>> import pandas as pd >>> import numpy as np Let's consider the following matrix \begin{equation} data = \left( \begin{array}{ccc} 1 & 2 & 3 & 4 \\\\ 5 & 6 & 7 & 8 \\\\ 9 & 10 & 11 & 12 \end{array}\right) \end{equation} >>> data = np.arange(1,13) >>> data = data.reshape(3,4) >>> data array([[ 1, 2, 3, 4], [ 5 ...

How to create and initialize a matrix in python using numpy ?

Daidalos October 11, 2019

Creative Commons License

To create and initialize a matrix in python, there are several solutions, some commons examples using the python module numpy: [TOC] ### Create a simple matrix Create a 1D matrix of 9 elements: \begin{equation} A = \left( \begin{array}{ccc} 1&7& 3& 7& 3& 6& 4& 9& 5 \end{array}\right) \end{equation} >>> import numpy as np >>> A = np.array([1,7,3,7,3,6,4,9,5]) >>> A array([1, 7, 3, 7, 3, 6, 4, 9, 5]) Notice: the shape of the matrix A is here (9,) and not (9,1) >>> ...

How to create a list of uniformly spaced numbers using a logarithmic scale with python ?

Daidalos October 10, 2019

Creative Commons License

Example of how to create a list of uniformly spaced numbers using a logarithmic scale with python: [TOC] ### Using the numpy function logspace Let's create a list of 100 uniformly spaced numbers (between $10^{0.1}$ et $10^{3}$) using a logarithmic scale >>> import numpy as np >>> l = np.logspace(0.1, 3, 100, endpoint=True) >>> l array([ 1.25892541, 1.34676844, 1.44074081, 1.54127022, 1.64881419, 1.76386217, 1.88693776, 2.0 ...

How to find the indexes of the minimum or maximum value(s) in a matrix using python ?

Daidalos October 08, 2019

Creative Commons License

Examples of how to find the indexes of the minimum or maximum value(s) in a matrix using python and the numpy function called [where](https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html): [TOC] Let's consider the following 2D matrix: >>> import numpy as np >>> A = np.random.randint(100, size=(4, 4)) >>> A array([[73, 37, 6, 21], [16, 53, 77, 44], [98, 95, 3, 29], [77, 67, 87, 86]]) ### Find min and max values First, to find the minimum ...

Aqua MODIS Band 6 missing pixels restoration using Gaussian processes

Ben October 08, 2019

Creative Commons License

Ongoing research ... Goal: To develop an algorithm (in python) based on Gaussian processes to restore the Aqua MODIS Band 6 missing pixels: [images:modis-band6-missing-data-restoration-01;modis-band6-missing-data-restoration-11 dim:1*2 size:80 caption:Aqua MODIS Band 6 missing pixels restoration using Gaussian processes] [TOC] ### Get and plot the data #!/usr/bin/env python from pyhdf.SD import SD, SDC from pylab import figure, cm import numpy as np import matplotlib ...

How to delete rows with values ​​below and above a minimum and maximum value in a pandas data frame ?

Daidalos October 05, 2019

Creative Commons License

A solution to delete rows with values ​​below and above a minimum and maximum value in a pandas data frame is to use the function [between()](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.between.html). Let's consider the following data frame >>> import pandas as pd >>> data = {'Label':['a','b','c','d','e','f','g','h','i','j'],'Value 1':[0,9,3,7,2,6,5,9,6,3], 'Value 2':[56,34,99,11,78,89,34,94,65,36]} >>> df = pd.DataFrame(data) >>> df Label Value 1 V ...

How to convert a pdf document pages to images using python ?

Daidalos October 01, 2019

Creative Commons License

Examples of how to convert a pdf document pages to images using python [TOC] ## 1. Using the python module pdf2image The python module pdf2image is available on [github](https://github.com/Belval/pdf2image). To install it a solution is to use pip: pip install pdf2image Note: the module needs poppler to run. If you use anaconda python distrubtion, it can be installed for example using the following command: conda install -c conda-forge poppler Then the module can now ...

How to create a matrix of random integers in python ?

Daidalos October 01, 2019

Creative Commons License

To create a matrix of random integers in python, a solution is to use the numpy function [randint](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.random.randint.html), examples: [TOC] ### 1D matrix with random integers between 0 and 9: Example of 1D matrix with 20 random integers between 0 and 9: >>> import numpy as np >>> A = np.random.randint(10, size=(20)) >>> A array([1, 8, 4, 3, 5, 7, 1, 2, 9, 6, 7, 6, 3, 1, 4, 6, 4, 9, 9, 6]) returns for example: ...

How to use Gaussian processes in machine learning to do a regression or classification using python 3 ?

Daidalos August 08, 2019

Creative Commons License

Examples of how to use Gaussian processes in machine learning to do a regression or classification using python 3: [TOC] ### A 1D example: from numpy.linalg import inv import matplotlib.pyplot as plt import numpy as np X = np.array([1., 3., 5., 6., 7., 8.]) Y = X * np.sin(X) X = X[:,np.newaxis] sigma_n = 1.5 plt.grid(True,linestyle='--') plt.errorbar(X, Y, yerr=sigma_n, fmt='o') plt.title('Gaussian Processes for regression (1D Case) Training Data', f ...

How to add a number to a matrix diagonal elements in python ?

Daidalos August 06, 2019

Creative Commons License

Example of how to add a number to a matrix diagonal elements in python ? [TOC] ### Replace the diagonal element by a same number To replace the diagonal element by a same number, a solution is to use the numpy function [numpy.fill_diagonal](https://docs.scipy.org/doc/numpy/reference/generated/numpy.fill_diagonal.html) >>> import numpy as np >>> A = np.arange(9).reshape(3,3) >>> A array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> np.fill_diagonal(A, 100) >>> A arra ...

How to perform mathematical operations on array elements in python ?

Daidalos August 02, 2019

Creative Commons License

Examples of how to perform mathematical operations on array elements ("element-wise operations") in python: [TOC] ### Add a number to all the elements of an array Let's consider the following array: \begin{equation} A = \left( \begin{array}{ccc} 0 & 1 & 2 \\\\ 3 & 4 & 5 \\\\ 6 & 7 & 8 \end{array}\right) \end{equation} >>> import numpy as np >>> A = np.arange(9).reshape(3,3) >>> A array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) to add a constant number, a s ...

How to add / sum the elements of an array in python ?

Daidalos July 31, 2019

Creative Commons License

To sum the elements of an array in python, a solution is to use the numpy function [sum](http://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html), example: [TOC] ### Sum all elements >>> import numpy as np >>> M = np.array([[1, 2], [3, 4]]) >>> M array([[1, 2], [3, 4]]) >>> np.sum(M) 10 Can be used with real numbers as well: >>> M = np.array([[1.0, 2.0], [3.1, 4.4]]) >>> np.sum(M) 10.5 ### Sum elements ov ...

How to change the size of axis labels in matplotlib ?

Daidalos July 31, 2019

Creative Commons License

Examples of how to change the size of axis labels in matplotlib: [TOC] ### Change the size of x-axis labels A solution to change the size of x-axis labels is to use the pyplot function [xticks](https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.xticks): matplotlib.pyplot.xticks(fontsize=14) example: #!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt import math pi = math.pi x_list = np.arange(-2*pi,2*pi,0.1) y_list = [math. ...

How to calculate a root mean square using python ?

Daidalos July 31, 2019

Creative Commons License

An example of how to calculate a root mean square using python in the case of a linear regression model: \begin{equation} y = \theta_1 x + \theta_0 \end{equation} [TOC] ### Plot the data Let's generate an ensemble of data with: \begin{equation} y = 3x + 2 \end{equation} import matplotlib.pyplot as plt import numpy as np X = 4 * np.random.rand(1000,1) X_b = np.c_[np.ones((1000,1)), X] Y = 2 + 3 * X + np.random.randn(1000,1) plt.plot(X,Y,'.') plt.x ...

How to plot a dashed line in matplotlib ?

Daidalos July 25, 2019

Creative Commons License

Examples of how to plot dashed lines in matplotlib: [TOC] ### Plot a dashed line To plot a dashed line a solution is to add '--'' ':' or '-:', example: import matplotlib.pyplot as plt x = [1,10] y = [3,6] plt.plot(x,y,'--') plt.savefig('DashedLine_01.png') plt.show() [image:524 size:50 caption:How to plot a dashed line in matplotlib using '--'] import matplotlib.pyplot as plt x = [1,10] y = [3,6] plt.plot(x,y,':') plt.savefig('DashedLine_02.p ...

How to put axis in polar coordinates in matplotlib ?

Daidalos July 25, 2019

Creative Commons License

Examples of how to put axis in polar coordinates in matplotlib: [TOC] ### Axis in polar coordinates To put the axis in polar coordinates in matplotlib, a solution is to use the option projection='polar', example: [image:polar-coordinates-01 size:50 caption:How to put axis in polar coordinates in matplotlib ?] import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111, projection='polar') plt.savefig("polar_coordinates_01.png", bbox_inches='tight') ...

How to plot MODIS cloud re and tau LUT (Nakajima and King's diagram) using python ?

Ben June 27, 2019

Creative Commons License

An example of how to plot MODIS cloud re and tau LUT (Nakajima and King's plot) in python using matplotlib: [TOC] ### How to get and read the Data Note: the LUTs are available [here](https://modis-atmosphere.gsfc.nasa.gov/products/cloud/luts) from pyhdf.SD import SD, SDC from scipy import interpolate import matplotlib.pyplot as plt import numpy as np import math import matplotlib.patches as mpatches import matplotlib.cm as cm file = SD('./MODIS_C6_LUTS/examples/oc ...

How to write a simple python code to find the intersection point between two straight lines ?

Daidalos June 21, 2019

Creative Commons License

Example of how to write a simple python code to find the intersection point between two straight lines: [TOC] ### Plot the lines import matplotlib.pyplot as plt import numpy as np m1, b1 = 1.0, 2.0 # slope & intercept (line 1) m2, b2 = 4.0, -3.0 # slope & intercept (line 2) x = np.linspace(-10,10,500) plt.plot(x,x*m1+b1) plt.plot(x,x*m2+b2) plt.xlim(-2,8) plt.ylim(-2,8) plt.title('How to find the intersection of two straight lines ?', fontsize=8) plt.gr ...

How to plot horizontal lines with matplotlib ?

Daidalos June 21, 2019

Creative Commons License

Examples of how to plot horizontal lines with matplotlib: [TOC] ### Plot horizontal lines To plot horizontal lines, a solution is to use axhline, example [image:matplotlib-horizontal-line-01 size:50 caption:How to plot horizontal lines with matplotlib ?] import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 2*np.pi, 1000) y1 = np.sin(x) f = plt.figure() ax = f.add_subplot(111) plt.plot(x, y1) plt.axhline(y=0.5) plt.axhline(y=-0.5) plt ...

How to plot an angle in python using matplotlib ?

Daidalos June 18, 2019

Creative Commons License

An example step by step of how to plot an angle in python using matplotlib and basic mathematics: [TOC] ### Define two lines [image:plot-an-angle-matplotlib-01 size:50 caption:How to plot an angle in python using matplotlib ?] import matplotlib.pyplot as plt import numpy as np m1, b1 = 0.1, 2.0 # slope & intercept (line 1) m2, b2 = 2.0, -3.0 # slope & intercept (line 2) x = np.linspace(-10,10,500) plt.plot(x,x*m1+b1) plt.plot(x,x*m2+b2) plt.xlim(-2,8) plt.yl ...

How to plot a circle in python using matplotlib ?

Daidalos June 18, 2019

Creative Commons License

Examples of how to plot a circle in python using matplotlib: [TOC] ### Plot a circle using plot() To plot a circle a first solution is to use the function plot(): [image:plot-circle-matplotlib-01 size:50 caption:How to plot a circle in python using matplotlib ?] import numpy as np import matplotlib.pyplot as plt theta = np.linspace(0, 2*np.pi, 100) r = np.sqrt(1.0) x1 = r*np.cos(theta) x2 = r*np.sin(theta) fig, ax = plt.subplots(1) ax.plot(x1, x2) ax.se ...

How to convert radians to degrees and vice versa in python ?

Daidalos June 18, 2019

Creative Commons License

Examples of how to convert radians to degrees and vice versa in python: [TOC] ### Convert radians to degrees using the math module A first solution is to use the python module [math](https://docs.python.org/2/library/math.html), example: >>> import math >>> math.radians(90) 1.5707963267948966 >>> math.pi / 2.0 1.5707963267948966 >>> math.radians(180) 3.141592653589793 Conversion radian -> degrees: >>> math.degrees(math.pi/2.0) 90.0 ...

How to subtract a number to each element of a matrix in python ?

Daidalos June 13, 2019

Creative Commons License

Examples of how to subtract a number to each element of a matrix in python using numpy: [TOC] ### Using - operator A solution is to use the - operator, example: >>> import numpy as np >>> a = np.array(([1,2,3],[4,5,6],[7,8,9])) >>> a array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> a = a - 1 >>> a array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) ### Avec la function numpy subtract() Another solution is to use the numpy function [subtract](https://do ...

How to multiply the elements of an array by a number in python ?

Daidalos June 13, 2019

Creative Commons License

To multiply the elements of an array by a number in python, a solution is to use the * operator, example: >>> import numpy as np >>> A = np.array([[1,2,0],[4,3,-1]]) >>> A array([[ 1, 2, 0], [ 4, 3, -1]]) >>> A * 2 array([[ 2, 4, 0], [ 8, 6, -2]]) ### References Liens | Site ------------- | ------------- [Introduction to Python Operator](https://data-flair.training/blogs/python-operator/) | data-flair.training ...

How to add a number to each element of a matrix in python ?

Daidalos June 13, 2019

Creative Commons License

Examples of how to add a number to each element of a matrix in python using numpy: [TOC] ### Using + operator A solution is to use the + operator, example: >>> import numpy as np >>> a = np.array(([1,2,3],[4,5,6],[7,8,9])) >>> a array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> a = a + 1 >>> a array([[ 2, 3, 4], [ 5, 6, 7], [ 8, 9, 10]]) ### Avec la function numpy add() Another solution is to use the numpy function [add](https://docs.scipy.o ...

How to pass an array or a list into a function in python ?

Daidalos June 13, 2019

Creative Commons License

Examples of how to pass an array or list as an argument of a function in python: [TOC] ### Pass a matrix in a function In python, it is possible to pass a matrix as an argument of a function, example: >>> import numpy as np >>> def function( x ): ... return 0.5 * x + 2 ... >>> x = np.arange(0,10,0.1) >>> y = function(x) >>> y array([ 2. , 2.05, 2.1 , 2.15, 2.2 , 2.25, 2.3 , 2.35, 2.4 , 2.45, 2.5 , 2.55, 2.6 , 2.65 ...

How to create a form in html with an image in background ?

Daidalos June 12, 2019

Creative Commons License

Example of how to create a form in html with an image in background (the form position can be changed using the position parameters left: 100px; top: 250px; ) [image:form-with-background-image size:50 caption: How to create a form in html with an image in background ?] <!DOCTYPE html> <html> <body> <form style="position: relative;" method="GET" action=""> <img src="Lenna.png" /> <div style="position: absolute; left: 100px; top: 250px;"> <input type="text" placeholder= ...

How to find the product of two matrices in python ?

Daidalos June 10, 2019

Creative Commons License

Examples of how to find the product of two matrices in python: [TOC] ### Function dot() To get the product of two matrices, a solution is to use the numpy function [dot()](https://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html): \begin{equation} A = \left( \begin{array}{ccc} 1 & 2 & 0 \\\\ 4 & 3 & -1 \end{array}\right) \end{equation} \begin{equation} B = \left( \begin{array}{ccc} 5 & 1 \\\\ 2 & 3 \\\\ 3 & 4 \end{array}\right) \end{equation} \beg ...

How to fix with a Django based website the AdSense: Earnings at risk - One or more of your sites does not have an ads.txt file ?

Daidalos June 09, 2019

Creative Commons License

Example of quickly fix with a django based web site the google Adsense warning message: "Earnings at risk - One or more of your sites does not have an ads.txt file". Just add the following url: url(r'^ads\.txt$', views.authorized_digital_sellers_view, name='authorized_digital_sellers'), and add the view: def authorized_digital_sellers_view(request): return HttpResponse('google.com, pub-0000000000000000, DIRECT, f08c47fec0942fa0') replace pub-0000000000000000 by your publisher i ...

How to color an area on a global map using python and basemap ?

Daidalos June 07, 2019

Creative Commons License

Examples of how to color an area on a global map using python and basemap: [TOC] ### Plot a rectangular area Using the function polygon (source: [simple_basemap_example.py](https://gist.github.com/blaylockbk/79658bdde8c1334ab88d3a67c6e57477)) [image:plot-world-map-using-matplotlib-03 size:50 caption:How to color an area on a global map using python and basemap ?] from mpl_toolkits.basemap import Basemap from matplotlib.patches import Polygon from matplotlib.collections import ...

How to iterate over two lists or more in python ?

Daidalos June 06, 2019

Creative Commons License

Examples of how to iterate over two lists or more in python [TOC] ### Iterate over two lists of same size A simple solution is to use the function [zip](https://docs.python.org/2/library/functions.html#zip) >>> l1 = ['a','b','c'] >>> l2 = [1,2,3] >>> for x,y in zip(l1,l2): ... print(x,y) ... a 1 b 2 c 3 ### Iterate over three lists of same size Another example: >>> l1 = ['a','b','c'] >>> l2 = [1,2,3] >>> l3 = ['hello','hi','bye'] >>> for x,y,z in z ...

How to get all the eMAS granule names from the ORACLES campaign using python 3 ?

Ben May 31, 2019

Creative Commons License

Example of how to get all the (MODIS Airborne Simulator) eMAS granule names from the ORACLES campaign using python: [TOC] ### Get ORACLES campaign days First step, let's download, using python, the json file at the root of the eMAS ORACLES campaign available [here](https://ladsweb.modaps.eosdis.nasa.gov/archive/MAS_eMAS/ORACLES/): import urllib.request, json ladsweb_url = 'https://ladsweb.modaps.eosdis.nasa.gov/archive/MAS_eMAS/ORACLES.json' with urllib.request.urlopen(lads ...

How to test if debug is true or false in a template with django ?

Daidalos May 29, 2019

Creative Commons License

Examples of how to test if debug is true or false in a template with django: [TOC] ### Approach 1 If only few templates are going to use the flag DEBUG a simple solution is to do in the file views.py: from django.conf import settings def my_view(request): debug_flag = settings.DEBUG context = {'debug_flag':debug_flag} return render(request, "my_app/my_template.html", context ) We can then use the debug flag in the template "my_template.html": {% if debug_flag % ...

How to add a title (label) on x and y-axis using python basemap module ?

Daidalos May 28, 2019

Creative Commons License

To add labels on x and y-axis while using basemap, a solution is to use the pyplot functions xlabel() and/or ylabel(): plt.xlabel('Longitude', labelpad=40) plt.ylabel('Latitude', labelpad=40) Note: the option labelpad allows to adjust the distance between the label and the axis. [image:plot-world-map-using-matplotlib-02 size:50 caption:How to add a title (label) on x and y-axis using python basemap module ?] from mpl_toolkits.basemap import Basemap import numpy as np import m ...

How to put the y-axis in logarithmic scale with Matplotlib ?

Daidalos May 26, 2019

Creative Commons License

To transform an axis in logarithmic scale with Matplotlib, a solution is to use the pyplot functions xscale and yscale: [TOC] ### Example 1 Let's take for example the exponential function: import matplotlib.pyplot as plt import numpy as np x_min = 0 x_max = 10.0 x = np.arange(x_min, x_max, .01) y = np.exp(x) plt.plot(x,y) plt.xlim(x_min,x_max) plt.ylim(np.exp(x_min),np.exp(x_max)) plt.grid(True,which="both", linestyle='--') plt.title('How to add a gr ...

How to add a grid on a figure in matplotlib ?

Daidalos May 26, 2019

Creative Commons License

Examples of how to add a grid on a figure in matplotlib [TOC] ### Using grid() function To add a grid in the background on a figure in matplotlib, a solution is to use the pyplot function [grid()](http://matplotlib.org/api/pyplot_api.html) pour connaitre l'ensemble des arguments possibles). Example: [image:454 size:50 caption:How to add a grid on a figure in matplotlib ?] import matplotlib.pyplot as plt import numpy as np x = np.arange(-5,5, .01) y = np.sin(2*np.pi*x) ...

How to change imshow axis values (labels) in matplotlib ?

Daidalos May 24, 2019

Creative Commons License

Examples of how to change imshow axis values (labels) in matplotlib: [TOC] Let's consider a simple figure using matplotlib imshow 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) plt.colorbar() plt.title('How to change imshow axis values with matplotlib ?', fontsize=8) plt.savefig("imshow_change_values_on_axis_01.png", bbox_inches='tight') ...

How to get a list of files located in a folder using python ?

Daidalos May 21, 2019

Creative Commons License

Examples of how to get a list of files located in a folder using python: [TOC] ### Using listdir() function Lets assume a folder that contains: dir01/ dir02/ fich01.txt fich02.txt fich02.txt To get a list of files located in the current folder using python a first solution is to use [os.listdir()](https://docs.python.org/2/library/os.html#os.listdir): >>> import os >>> list = os.listdir('.') >>> print(list) [dir01,dir02,fich01.txt,fich ...

How to download a web pdf file from its url in python ?

Daidalos May 21, 2019

Creative Commons License

To download a pdf from a given web url using python, a solution is to use the module [urllib](https://docs.python.org/2/library/urllib.html). Lets try to download the file available from the following url http://math.univ-toulouse.fr/~besse/Wikistat/pdf/st-intro.pdf using urlretrieve: >>> import urllib >>> urllib.urlretrieve('http://math.univ-toulouse.fr/~besse/Wikistat/pdf/st-intro.pdf', "st-intro.pdf") Note: it is also possible to directly change the name of the file ( ...

How to create a list of files with a given extension (.txt, .avi, .docx, etc) in python ?

Daidalos May 21, 2019

Creative Commons License

Example of how to create a list of files with a given extension in python. Lets assume we want to create a list of all the files with the extensions '.hdf' in a folder called 'output': ./output/ MYD06_L2.A2014038.2300.061.2018052102433.hdf MYD06_L2.A2014033.1930.061.2018052042944.hdf MYD06_L2.A2014046.2210.061.2018052112538.hdf MYD06_L2.A2014058.2235.061.2018052141003.hdf MYD06_L2.A2014037.2045.061.2018052094723.hdf MYD06_L2.A2014054.2125.061.2018052131042.hdf MYD06_L2.A ...

How to change imshow aspect ratio and fit the colorbar size in matplotlib ?

Daidalos May 20, 2019

Creative Commons License

An example of how to change imshow aspect ratio and adjust the colorbar accordingly in matplotlib: [image:imshow-extent-custum-aspect-ratio-00 size:50 caption:Comment changer la forme d'une figure imshow et avoir la barre de couleurs de même taille avec matplotlib ?] import numpy as np import matplotlib.pyplot as plt data = np.random.rand(50,1000) plt.imshow(data) plt.colorbar() plt.savefig("imshow_extent_custum_aspect_ratio_00.png", bbox_inches='tight') plt.close() ...

How to change imshow aspect ratio in matplotlib ?

Daidalos May 20, 2019

Creative Commons License

Examples of how to change imshow aspect ratio in matplotlib: [TOC] Matplotlib imshow function can return figures with very elongated shapes, example: import numpy as np import matplotlib.pyplot as plt data = np.random.rand(50,1000) plt.imshow(data, extent=[-1,1,-10,10]) plt.savefig("imshow_extent_custum_aspect_ratio_01.png", bbox_inches='tight') plt.close() [image:imshow-extent-custum-aspect-ratio-01 size:30 caption:How to change imshow aspect ratio in matplotlib ?] ...

How to show in a template the number of online visitors with Django ?

Daidalos May 14, 2019

Creative Commons License

An example of solution to display in a template the number of online visitors in a django web site: [TOC] ### Create a table Visitor_Infos First, create a table in models.py called for example: Visitor_Infos: class Visitor_Infos(models.Model): ip_address = models.GenericIPAddressField() page_visited = models.TextField() event_date = models.DateTimeField(default=datetime.now) ### Edit/create the file processor.py Edit the context file processor.py: from django.conf ...

How to create a 2d histogram with matplotlib ?

Daidalos May 14, 2019

Creative Commons License

Examples of how to create a 2d histogram with matplotlib [TOC] ### Using the matplotlib hist2d function To create a 2d histogram in python there are several solutions: for example there is the matplotlib function [hist2d](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.hist2d.html). from numpy import c_ import numpy as np import matplotlib.pyplot as plt import random n = 100000 x = np.random.standard_normal(n) y = 3.0 * x + 2.0 * np.random.standard_normal(n) ...

How to create a json file with the names and attributes of a VIIRS L2 CLDPROP netcdf file using python 3 ?

Ben May 10, 2019

Creative Commons License

Example of python 3 code to save in a json file the names and attributes of a VIIRS L2 CLDPROP netcdf file. [TOC] Note: the json file created can be found [here](/Files/viirs-cldprop-l2-001-names-attributes/) ### Read the file import netCDF4 import numpy as np import json import pprint f = netCDF4.Dataset('CLDPROP_L2_VIIRS_SNPP.A2018046.1436.001.2019068074007.nc') ### Get all group names group_dic = f.groups.keys() ### Get names and attributes in each group ...

How to download a VIIRS L2 CLDPROP netcdf file from ladsweb using python ?

Ben May 09, 2019

Creative Commons License

Example of python script to download on your local machine a VIIRS L2 CLDPROP netcdf granule file from [ladsweb](https://ladsweb.modaps.eosdis.nasa.gov/search/) using python. [TOC] Lets consider the following data for example: year = 2018 month = 2 day = 15 hour = 14 minute = 36 Note: VIIRS granules are every 6 minutes ### Convert day to count of days First step we need to get the count of days: from datetime import date d0 = date(year, 1, 1) d1 = date(year ...

How to get visitor ip address for a django project ?

Daidalos May 07, 2019

Creative Commons License

Example of how to get visitor ip address for a django project: [TOC] ### Get visitor ip address def visitor_ip_address(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip ### Check if ip address is valid To check if the ip address is valid, a solution is to use the [socket](h ...

How to reverse columns order in a table with python ?

Daidalos May 07, 2019

Creative Commons License

Example of how to reverse columns order in a table with python: let's consider the following table: >>> import numpy as np >>> table = np.array([[0., 1., 2., 3., 4., 5., 6., 7.], ... [6., 6., 4., 9., 7., 5., 4., 8.], ... [4., 9., 3., 7., 5., 2., 3., 1.], ... [6., 9., 8., 1., 4., 3., 2., 1.], ... [4., 8., 7., 6., 1., 7., 1., 1.]]) \begin{equation} \begin{array}{cccccc} 0. & 1. & 2. & 3. & 4. & 5. & 6. & 7.\\\\ 6. & 6. & 4. & 9. & 7. & ...

How to reverse rows order in a table with python ?

Daidalos April 23, 2019

Creative Commons License

Examples of how to reverse rows order in a table with python. Let's consider a random table: >>> import numpy as np >>> table = np.array([[0., 4., 4., 2., 7., 0.], ... [1., 2., 7., 2., 3., 4.], ... [2., 2., 3., 3., 6., 3.], ... [3., 9., 0., 6., 3., 3.], ... [4., 3., 1., 8., 2., 5.], ... [5., 9., 3., 7., 6., 8.], ... [6., 9., 5., 8., 1., 8.], ... [7., 9., 6., 7., 3., 7.], ... [8., 2., 1., 4., 4., 8.], ... [9., ...

How to find the minimum or maximum value in a matrix with python ?

Daidalos April 22, 2019

Creative Commons License

Examples of how to find the minimum and maximum values in a matrix using numpy and python: [TOC] ### Approach 1: To find the minimum and maximum values in an array, a solution is to use the numpy functions max() and min(): >>> import numpy as np >>> A = np.array(([2,7,-1],[1,9,8],[-1,5,6])) >>> A array([[ 2, 7, -1], [ 1, 9, 8], [-1, 5, 6]]) >>> np.min(A) -1 >>> np.max(A) 9 ### Approach 2: Another solutio ...

Search