Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Working with Numpy

From the NumPy documentation:

NumPy is the fundamental package for scientific computing in Python. It is a Python library that provides a multidimensional array object, various derived objects (such as masked arrays and matrices), and an assortment of routines for fast operations on arrays, including mathematical, logical, shape manipulation, sorting, selecting, I/O, discrete Fourier transforms, basic linear algebra, basic statistical operations, random simulation, and much more.

NumPy’s position at the center of the scientific Python ecosystem means that all users should start here in their learning journey through the core scientific packages.

Additional Tutorials:

What is the difference between regular Python and Numpy Python?

Data Types

Python has specific data types, but not as many as traditional C or FORTRAN

Numpy can be thought of as a space within the Python language whith more data types like C or FORTRAN and a richer set of mathematical/computational enivironment built on top of the base Python environment. All the regular Python functions still exsits just more options are available.

Numpy is based on arrays of data, with all values having the same data type in the array. This greatly increases computational performance. Can convert between basic Python and Numpy data space easily and quickly.

Basic Python vs Numpy performance

Basic Python can perform computations relativly fast.

The computation can be faster for some applications using list comprehensions. This is performing the same computation just with a diffrent syntax performing the computations in a more optimized way.

Switching between Basic Python space and Numpy space

Create some data using Python lists

Convert the python list into numpy array

Convert the numpy array back into python list

Making Numpy Arrays

Numpy also comes with a large number of methods to create data arrays so you don’t have to. Chances are Numpy has a method to do what you want, so search there first.

Indexing, Slicing, Broadcasging

How to get the specific data from the Numpy array. Numpy uses the same slicing as Python lists. Start number to but not including end number.

One of the most important features of Numpy is Broadcasting, where a single operation is performed on all values of the Numpy array without the need for a loop. This creates more simple and readable code, and is significantly faster. General rule is if it’s possble to remove a loop by Broadcasting, do it!

Create an array of all zeros

Add a value of 1 to every value in the array. Also notice that the initial array was of type integer. But we are adding a float so all vales are first upconverted to type float and then a value of 1.0 is added to every value in the array.

Here we change the data type of the entire array from float to integer.

Here we add a value to a subset of the array by adding 10 to values matching index from 3 to 7. The rest of the values are unchanged.

Here we use shorthand notiation to add a constant of 1000 to every value in the array.

The IEEE Not A Number value

There is a special Numpy value called NaN which is used in calculations to represent a value that is not a number. Think of it as missing data, or a bad value that should not be propigated through the data. One of the most important things to remember about NaN is that it taints anything it touches!

Because NaN is special, it acts funny. Looking for NaN requires some specific logic.

Will need to use the Numpy methods of searching the arrays if you want to do comparisons for find where NaNs are located

To use NaNs properly requries a litte bit of extra thought, but is greatly worth it!

Now we will assign a value in the Numpy array to NaN

Calculate the mean. Notice how it returns NaN. The NaNs are tainting all the operations.

We need to use a different method that understands how to correctly handle NaNs

Working with time in Numpy

If you deal with time series data you will need to work with time data types. Oh that’s right, most atmospheric data is time series data...

Python has a library called datetime that is great for working with dates and times. It is timezone unaware and works on one value at a time. This is a native data type within Python and you will see it all over the place. Here are some quick examples.

Get the datetime now.

Or get the datetime in UTC timezone.

Or from a timestamp of number of seconds from Epoch, Seconds from 1970-01-01 00:00:00: UTC

But when working with a lot of time samples we need to use the Numpy time data type. It can take in a string and convert to a Numpy datetime64 value. Notice when it prints out, it will print out in ISO format.

To just get the date right now

To get the date and time right now. Notice the time is in UTC. Most likely this is what you want, if not understand how to get what you want.

The default is store the precision at the level of input. But we can update the precison by setting precision when setting the value or after the value is created to the desired precision.

OK so what you can set precisoin. Why do I care? Because you can use the precision to indicate what step size to use. Notice the following range did not provide a starting or ending day. This helps with not needing to know length of months.

There is also a a timedelta64 data type that is the result of differencing times.

Time Deltas are important for adding or subtracting times.

Converting between Python datetime and Numpy datetime64

At some point you will need to convert a time value from one space to another. Don’t memorize this, just remember it exists and where you can find the code.

It is a bit more complicated to convert from Numpy datetime64 to Python datetime