RSS Amplifier

CodeDrome · Jun 23, 2026

A NumPy Cheat Sheet

0
Sign in to vote or save

Chris Webb · CodeDrome

NumPy is a large and complex library and most users will only need a small subset of its functionality. It is very well documented here but I often find it useful to keep snippets or bits of sample code, especially for features I need occasionally but not frequently enough to commit to memory. The code for this article consists of a Python file containing a number of such snippets which can be copied, pasted and edited for specific situations. You may or may not find them useful but that is not the point - the purpose of this article is to encourage and inspire you to create and maintain your own cheatsheet.

If you are not already a NumPy user you might like to read my introductory NumPy Reference.

This project consists of a single file called numpycheatsheet.py which you can find in the Github repository. Please feel free to edit and adapt it to your own needs. Each NumPy feature covered by this article has its own function in the file; just uncomment the one you want to run in the main function. I have chosen a selection of common tasks which I feel will cover the majority of what a typical NumPy programmer will need on a day to day basis.

The code snippets all assume NumPy has been aliased as np, the usual convention.

You might occasionally need to check the version of NumPy you have installed. To do this simply grab the np.__version__ property.

There are several ways to create a NumPy array including from a Python list or with the zeros or ones methods which create an array filled with 0s or 1s respectively.

NumPy contains methods to calculate a variety of statistics including arithmetic mean, sum, minimum and maximum etc. These can be called on NumPy (np) like this np.sum(data) or on a NumPy array like this data.sum().

There are a few methods to get information about an array including ndim (number of dimensions), size (total number of elements) and dtype (data type).

The unique method returns a sorted array of unique values, ie. it “de-dupes” the values.

The savetxt and loadtxt methods respectively save an array to a CSV file and create an array from a CSV file. As with any code that attempts to interact with the outside world, even the local file system, calls to these two methods should be in try/except blocks.

A NumPy array has a data type depending on its contents. In general you can let NumPy figure out the type for itself but you can specify the type when creating an array and, as we saw in the info function, you can read the dtype property.

It’s sometimes useful to explicitly iterate the values in an array, for example when printing the values in a format other than the default. You can use a normal for/in loop or obtain an iterator with the nditer method. Note that operations on an array’s elements rarely if ever require an explicit loop and can be performed on the array as a single entity.

The where method returns an array of indices of the values in the input array satisfying the where clause; this can then be used to retrieve the actual values you want. I have included an alternative syntax with these two operations combined into a single line.

NumPy’s pseudo-random methods are useful for generating test or demo values, and include a handy Gaussian or normal distribution generator.

Possibly NumPy’s most useful feature is the ability to carry out operations on all elements of an array in a single line with no explicit looping. The code in the arithmetic function demonstrated adding, subtracting, multiplying and dividing two arrays as well as one array and a scalar. NumPy has methods called add, subtract, multiply and divide but I much prefer the good old fashioned +, -, * and / symbols.

This is another way of creating an array which I thought deserved its own function. The linspace (linear space) method creates an equally spaced range of values between a minimum and maximum.

The shape of an array is the number of values in each dimension, and the reshape method rearranges the existing values into the specified number of rows, columns or deeper dimensions.

These methods return True or False depending on whether all or any of the values in an array satisfy the condition.

Numpy provides us with sqrt and pow methods for square roots and powers but you can also use the standard Python ** syntax which I prefer.

The nth root of a number is the number to the power of 1/n, so for example the square root of a number is the number to the power of 1/2 or 0.5. I have included a demonstration of this in the sample code. NumPy also has a cbrt (cube root) method but if you are unlucky enough to need and other roots you will have to use the power of reciprocal technique.

The ...stack methods combine two or more arrays vertically (vstack) or horizontally (column_stack).

The append method creates a new array with the specified iterable or scalar appended. This is not an in-place operation so the return value must be assigned to a variable. In the code I have overwritten the original arrays with the return values of append but if you do not do this the original array is unchanged.

The flip method reverses an array but works across all dimensions, so for example a 2-dimensional array is reversed both horizontally and vertically.

I hope you found something useful in the sample code in numpycheatsheet.py and more importantly were inspired to create your own NumPy cheatsheet.

Leave a comment

For updates and random ramblings please follow me on Bluesky.

No AI was used in creating the code, text or images in this article.

Read the original on codedrome.substack.com

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.