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.

Starting with Scientific Libraries in Python

If you want to perform some larger scientific computations in Python some great libraries to use are:

  • Numpy = base building blocks for large array based computing

  • Pandas = Pandas is an extension of the Numpy data model to structure and organize data into Dataframes. A Dataframe resembles the look of a spreadsheet, but is much more powerful.

  • Xarray = Xarry is an extension of the Numpy and Pandas data model to structure and organize data into Dataset. A Dataset resembles the look of a netCDF3 data model, but is much more powerful.

Working with Pandas

Create Pandas Dataframe

Create some data in a Python dictionary

Use the dictionary to populate the new Pandas data frame. Python and Jupyter play very well with Pandas and when requested to print the Pandas Dataframe or Series Jupyter knows how to print in a visually appealing way. Notice the columns have names taken from the Dictionary keys we used to populate the Dataframe. Each row has an index set to an incremented integer by default.

A Dataframe has a concept of index to label the rows of the Dataframe and column names to label the Columns. We created column names from the dictionary keys used to initially create the Dataframe. We can create index labels in the Dataframe upon creation of the Dataframe.

Printing the column shows additional informatin including the index and data type. This is returned as a Pandas Series.

Extracting a row uses the .loc() method on the Dataframe. .loc() standar for location and searches the index for a match.

Can also extract using index location .iloc() method.

Read in some data

Using the path to a specific file we read the data into a Pandas Dataframe. This is something you will use very often if you have data in ASCII column files. Get to know this method well. The method has keywords to help describe how to read the column data including the delimter, number of header rows, and which column is the time stamp. If it can parse the time stamp it will convert to Pandas native time type.

Similar to Numpy, can use the .shape and .size methods on the Dataframe to return metadata about size of the Dataframe.

Print the first five rows using Numpy syntax

We can get the names of the columns with .columns method

Pandas has a few methods used to inspect the data in the Dataset or Series and present the typical statistical values. Because Pandas plays so well with Jupyter the output is very easy to visualize.

What type is the TIMESTAMP data? Notice that Pandas has a new data type of time specific to Pandas. This is similar to Datetime datetime and Numpy datetime64, but is technically different.

Get the pressure Series from the DataFrame and sum it up to one value and calcualte the mean.

Extract the RH series from the DataFrame. This is a copy of the Series in the DataFrame so changing the values will not change the values in the DataFrame.

Calculate a rolling mean over the Series using 10 points. Notice the first value is NaN. There is a default number of values to use to calculate a value. Else it is set to NaN. By specifically stating the minimum number of points to use when calculating the mean we force it to not fill in so many NaNs. There is at least two value to use in the rollig window so only first value is set to NaN. What happens when you change min_periods to a larger number?

Working with Xarray

Xarry is a class of objects added to the regular Python system that allows storing data in a more organized method. The format is very similar to netCDF classic model (netCDF3). It can read netCDF files efficiently and handle some issues associated with incorrectly designed netCDF files.

Xarray also has extetions to use the Numpy, Pandas, Dask and SciPy libaries directly. Think of Xarray as a tool for orgnaizing data in a way that other libaries can be used on the data efficiently.

A primary difference between Xarray and Pandas is that Pandas is designed to handle 1-D data while Xarray can handle n-D data and metadata about the data.

The one downside is that Xarry has very powerful functions with less great documentation. May need to dig a bit to get the best way to perform a task.

DataArray

Here we create some data with Numpy and put into an Xarray DataArray. Notice how there is a concept of dimentionality built into DataArray. “xarray.DataArray (dim_0: 10000)”. But because we didn’t define the dimention name a generic one was created for us. Also notice how nice the printing looks. Xarray plays very well with Jupyter.

This time create a time array to match the data array shape. Time will be one minute time steps. The time array will become a coordinate variable to describe the values along the dimention we defined and named “time”. The coordinate is set to the time array and the dimention is set to “time” string.

We can add attributes describing metadata about the data.

Same as above but all in one step while creating the DataArray.

To extract the data values only we use the .values attribute on the DataArray

To extract the attributes as a dictionary we use the .attrs attribute.

Or the attrs decorator can also accept a name for a specific attribute

Dataset

The full power of Xarray comes from using Datasets. A Dataset is a collection of DataArrays. The beauty of Datasets is holding all the corresoponding data together and performing functions on multiple DataArrays in the Datasets all at once. This becomes very powerful and extreemly fast!

Create some data and a time data array to match the data we created with minute time steps.

Print out one DataArray from the Dataset

Read in data

Let’s read in a single netCDF data file. Notice we are using relative paths to go one directory down into the data directory. This will also read in multiple files when provided a list of file names.

To resolve issues with incorrectly formatted variables or reduce the memory we can exclude some variable from being read.

We can perform the same operations of sum and mean on the DataArray as we did with the Pandas Series. Notice the returned value is a Numpy array of length one.

Sub-selecting data

Now let’s calculate the mean for a hour by grouping the data. This works for all time worded groups: day, hour, minute, year, month, ... The method returns a new Dataset and leaves the orginal untouched. Notice how data was orginanally type integer, but because we are calcualting a mean, the type is upconverted to float.

We can also define the grouping size by using the .resample() method and pass in the funciton to use using the .reduce() method. If there is no data to perform the operation, a new time step is added with a NaN data value.

The .sel() method select data based on data or coordinate values. We can extract a range of data by filtering on the time coordinate and using the builtin slice() function. This looks familar to the Pandas example because Xarray is using Pandas.

For selecting at specific index use .isel().

What if we want to find the closes value in time but not match to values outside a tolerable range. We can use .reindex() method with a toleracne to indicate which values should be matched. The values that don’t have a match are set to NaN. We need to use timedelta64() to set the tolerance value which includes a time unit. Anywhere the time is outside the tolerance the data values is set to NaN. To allow for setting NaN, the data type is upconverted to float.