Basic Python tricks
Inline if statement
Let’s get started with the simplest form. The multi-line if statement looks like this1:
|
|
The one-liner goes like this:
|
|
Let’s add another condition with an elif
. The multi-line version looks like this:
|
|
To do it in one line:
|
|
A multi-line nested if statement looks like this:
|
|
And the solution in one line:
|
|
This kind of multi-nesting can be avoided with a refractor or with the smart use of dictionaries and lists. You can read more on refractors to reduce nesting in CodeAesthetic’s video.
Examples of * and ** unpack operator in python
How to use the ** unpack operator as entry for functions
This one is cool to follow the DRY principle. I use it for repeated arguments for multiple plots in Matplotlib. You can set parameters to a function with a dictionary:
|
|
Unpacking list with the * operator
You can use unpack inside of another list. And feed that into a function:
|
|
You can also unpack the list as arguments of a function directly
|
|
For further reading on the *
python operator you can read W3schools
, This Pointer, and Finxter
Get all methods of an object
Given an object foo
use dir(foo)
to print all its methods like this:
|
|
Join multiple lines of a string into one long string
If you have a very long chain of characters, you can split it this way:
|
|
It can also be used to join multiple lines of text into a single one.
Importing modules from parent directories
Lets use this example:
|
|
if you want to import modules inside ../level1/level2
, you
need to add that directory to the sys.path:
|
|
Alternative and fast way of making loops
Using itertools
, you can create a loop without creating auxiliary variables or casting an iterable:
|
|
Add a True/False switch flag to a command line Python script
A little cheatsheet on how argparse works. I tend to use docopt
more now. But argparse is part of the python standard library so in some cases you may have no other option.
|
|
Usage example:
|
|
Other example:
|
|
Usage example:
|
|
If you ask script.py
to return the value asociated to -f
:
|
|
Output:
|
|
Some IPython magic tricks
|
|
Ipdb: Python debugger
Here we have a few shortkeys for the Ipdb python debugger 2:
|
|
Conda
Create a conda enviroment given a name, an enviroment yaml config file and the python version.
|
|
Pandas
check if is view
Not so good practice, it is a private attribute
|
|
Alternatively, comparing two DataFrames to determine if they have the same base.
|
|
Faster Pandas concatenation
Pandas is not optimized for dynamic concatenation. Instead of using a for loop like this one:
|
|
Use the appropiate pandas method concat
instead:
|
|
The same applies to appending new data to a pandas.DataFrame. It’s better to use the append
method than to do it dynamically.
(Source: StackOverflow , 26/8/2021)
Some good libraries
- docopt: Easiest way to create a CLI interface. Not fully POSIX. But it is blazing fast to implement.
- Scrapy: An open source and collaborative framework for extracting the data you need from websites. In a fast, simple, yet extensible way.
- Python gpu:
- saturncloud
- rapidsAI
- modin or cudf
- Differential equations
- scipy.odeint: Differential equations solver inside of scipy.
- JiTCDDE (just-in-time compilation for delay differential equations): Scipy-based module to solve Delay Differential Equations (DDE).
- diff equations: Basically, use generator -> use object -> search compact form.
NumPy
Be careful with NumPy
For a few hundred elements of data, it is actually faster to use a list (even more if it’s defined by comprehension), always test the difference for your particular application.
NumPy create array from iterator
|
|
Matplotlib and Seaborn
plotting backends
Matplotlib change font size
You can touch your matplotlibrc or do:
|
|
Create a random image with a colormap and a random matrix
Let’s create a random image. We insert 256 rows with 256 distinct colors in random order. This is in order to not have repeated colors inside of a row.
|
|
If you don’t care about repetitions inside the array, you can use this version:
|
|
Let’s display the image with no axis. I will save all images as SVG, but you can choose PNG, PDF or some compatible format:
|
|
We can sort each row of the image this way (sorting horizontally):
|
|
We can sort each column of the image this way (sorting vertically):
|
|
Likewise, we can sort the array as a whole and reshape (every value in order):
|
|
Large Matplotlib colormaps have white lines when saved as a file
You need to insert a True
on the rasterized argument like this:
|
|
Put the legend outside in a Matplotlib figure
First, let’s assign and tag the plots:
|
|
Then, assign the figures and titles:
|
|
After that, plot all the curves. Set the legend, adjust the plot to the right and save.
|
|
You can also do it by adjusting bbox_to_anchor:
|
|
Matplotlib interactive inside IPython
To allow IPython to print plots in a new window use this:
|
|
Or this:
|
|
Iterating trough colors: Plotting curves following a colormap
Plotting curves with different colors in a colormap is an accesible task with Python. First, we split the [0, 1]
interval in the amount of curves we are working with. Then we pick colors from a colormap in this case Gnuplot. In an example:
|
|
Delete all lines in the upper right corner of the plot box: Axis spine deletion
A simple aesthetic change. You can change the Matplotlib config file, or use a function like this if you have the axis:
|
|
This is a solution if you want to apply the solution to a single axis
I prefer the config file approach, that applies to every plot after is setted. You can see how I apply it in my other blog post.
Fix LaTeX Matplotlib errors
It can help to clear the cache 3:
|
|
Source: Matplotlib Docs
-
Python If-Else One-Liner Examples. (n.d.). Retrieved April 7, 2023, from https://www.golinuxcloud.com/python-if-else-one-line/ . ↩︎
-
Wang, C. (2017, July 12). ipdb cheat sheet. Retrieved April 7, 2023, from http://wangchuan.github.io/coding/2017/07/12/ipdb-cheat-sheet.html ↩︎
-
Matplotlib Troubleshooting FAQ. (n.d.). Retrieved April 7, 2023, from https://matplotlib.org/stable/faq/troubleshooting_faq.html#locating-matplotlib-config-dir ↩︎