Save plot to numpy array

This is a handy trick for unit tests and the like, when you need to do a pixel-to-pixel comparison with a saved plot. One way is to use fig.canvas.tostring_rgb and then numpy.fromstring with the approriate dtype. There are other ways as well, but this is the one I tend to use. E.g. import matplotlib.pyplot as … Read more

How is numpy’s fancy indexing implemented?

You have three questions: 1. Which __xx__ method has numpy overridden/defined to handle fancy indexing? The indexing operator [] is overridable using __getitem__, __setitem__, and __delitem__. It can be fun to write a simple subclass that offers some introspection: >>> class VerboseList(list): … def __getitem__(self, key): … print(key) … return super().__getitem__(key) … Let’s make an … Read more

Is there a standard solution for Gauss elimination in Python?

I finally found, that it can be done using LU decomposition. Here the U matrix represents the reduced form of the linear system. from numpy import array from scipy.linalg import lu a = array([[2.,4.,4.,4.],[1.,2.,3.,3.],[1.,2.,2.,2.],[1.,4.,3.,4.]]) pl, u = lu(a, permute_l=True) Then u reads array([[ 2., 4., 4., 4.], [ 0., 2., 1., 2.], [ 0., 0., … Read more

Parse a Pandas column to Datetime when importing table from SQL database and filtering rows by date

Pandas is aware of the object datetime but when you use some of the import functions it is taken as a string. So what you need to do is make sure the column is set as the datetime type not as a string. Then you can make your query. df[‘date’] = pd.to_datetime(df[‘date’]) df_masked = df[(df[‘date’] … Read more