Skip to content

Bamboo Weekly #198: Voyager 1 (solutions)

Get better at: Fixed-width fields, missing values, dates and times, plotting with Plotly

Bamboo Weekly #198: Voyager 1 (solutions)

This week, we looked at Voyager 1's journey, using NASA data. As of last week, Voyager 1 (https://en.wikipedia.org/wiki/Voyager_1) is the farthest human-made object from Earth, now 1 light day away from us. So yeah, it has taken nearly 50 years for it to get the same distance as light travels in one day.

Data and five questions

This week's data comes from NASA's "COHOWeb" (COrdinatad Heliospheric Observations ) site, at https://omniweb.gsfc.nasa.gov/coho/form/voyager1.html. The site provides data from a number of probes that NASA has launched over the years. Voyager 1 data can be downloaded from https://omniweb.gsfc.nasa.gov/coho/form/voyager1.html, by indicating the following on the form:

After submitting this form, you get both a data file (in fixed-width field format) and a data dictionary (with the names and types/sizes of the fields).

Note that NASA only updates this data set every year or two. That explains why the most recent data is from June of 2025.

Paid subscribers, both to Bamboo Weekly and to my LernerPython+data membership program (https://LernerPython.com) get all of the questions and answers, as well as downloadable data files, downloadable versions of my notebooks, one-click access to my notebooks, and invitations to monthly office hours.

Learning goals for this week include: Fixed-width fields, dates and times, plotting with Plotly, and dealing with missing values.

Here are my solutions and explanations for this week:

Read the data file into a Pandas data frame, ensuring that every column has a name (from the data dictionary) and is valid. Add a timestamp column (with a datetime dtype) reflecting the date and hour at which the measurement was taken. Turn missing values into NaN.

I started off, as usual, by importing Pandas and Plotly express:

import pandas as pd
from plotly import express as px

Most of the data we deal with at Bamboo Weekly is in CSV, Excel, or JSON format. But this week, we had to deal with fixed-width fields. This format used to be quite popular, I've heard, because it required less computation than the variable-length fields of CSV. Working with fixed-width fields means knowing precisely how wide each field is, and handing that to pd.read_fwf.

The fields are described to read_fwf as a list of 2-element tuples; each tuple represents the starting and ending point in the string, indexed using 0 and with the endpoint not included (like a Python slice). But I also needed to do two more things: First, I indicated that the first line did not contain headers (with header=None) and then provided header names with the names keyword argument:

filename = 'data/bw-198-voyager1.lst'

df = (
    pd
        .read_fwf(filename,
                  colspecs=[(0, 4),  # I4
                         (4, 8),   # I4
                         (8, 11),  # I3
                         (11, 18), # F7.2
                          (18, 25), # F7.1
                          (25, 32), # F7.1
                          (32, 40), # F8.3
                          (40, 47),  # F7.1
                          (47, 56),  # F9.5
                          (56, 65), # F9.0
                          (65, 75), # 10.3
                          (75, 85), # 10.3
                          (85, 93)  # F8.3
                         ],
                header=None, 
                names=['Year', 'DOY', 'Hour', 'Radial Distance',
                      'Lat Angle', 'Long Angle', 'Scalar B magnitude',
                      'Plasma speed', 'SW density fit', 'Temperature from fit',
                      'LECP', 'CRS', 'Bscalar_ERR'],
                )
)

This worked, in that it gave me a working data frame. But it's missing two pieces that I asked for. One, I wanted a timestamp column with a datetime dtype. To do that, I used assign to add a new column, and used lambda so that I could refer to the data frame on which we were running. I then used a combination of pd.to_datetime on the year, plus pd.to_timedelta on the day of the year, and then another pd.to_timedelta for the hour. This gave me hourly data about Voyager 1 using familiar, Earth-based dates and times:

filename = 'data/bw-198-voyager1.lst'

df = (
    pd
        .read_fwf(filename,
                  colspecs=[(0, 4),  # I4
                         (4, 8),   # I4
                         (8, 11),  # I3
                         (11, 18), # F7.2
                          (18, 25), # F7.1
                          (25, 32), # F7.1
                          (32, 40), # F8.3
                          (40, 47),  # F7.1
                          (47, 56),  # F9.5
                          (56, 65), # F9.0
                          (65, 75), # 10.3
                          (75, 85), # 10.3
                          (85, 93)  # F8.3
                         ],
                header=None, 
                names=['Year', 'DOY', 'Hour', 'Radial Distance',
                      'Lat Angle', 'Long Angle', 'Scalar B magnitude',
                      'Plasma speed', 'SW density fit', 'Temperature from fit',
                      'LECP', 'CRS', 'Bscalar_ERR'],
                )
    .assign(timestamp = lambda df_: pd.to_datetime(df_['Year'].astype(str), format='%Y')
              + pd.to_timedelta(df_['DOY'] - 1, unit='D')
              + pd.to_timedelta(df_['Hour'], unit='h'))
)

One final issue was missing data. This data set doesn't represent missing values with nothing, or with something like NA or NaN. Rather, it uses numbers in which all digits are 9s. I thus used replace, passing it a dict whose keys are all of the possible numbers, and indicated (with the dict's values) that I wanted to assign them pd.NA:

filename = 'data/bw-198-voyager1.lst'

df = (
    pd
        .read_fwf(filename,
                  colspecs=[(0, 4),  # I4
                         (4, 8),   # I4
                         (8, 11),  # I3
                         (11, 18), # F7.2
                          (18, 25), # F7.1
                          (25, 32), # F7.1
                          (32, 40), # F8.3
                          (40, 47),  # F7.1
                          (47, 56),  # F9.5
                          (56, 65), # F9.0
                          (65, 75), # 10.3
                          (75, 85), # 10.3
                          (85, 93)  # F8.3
                         ],
                header=None, 
                names=['Year', 'DOY', 'Hour', 'Radial Distance',
                      'Lat Angle', 'Long Angle', 'Scalar B magnitude',
                      'Plasma speed', 'SW density fit', 'Temperature from fit',
                      'LECP', 'CRS', 'Bscalar_ERR'],
                )
    .assign(timestamp = lambda df_: pd.to_datetime(df_['Year'].astype(str), format='%Y')
              + pd.to_timedelta(df_['DOY'] - 1, unit='D')
              + pd.to_timedelta(df_['Hour'], unit='h'))
    .replace({9999999:pd.NA,
             999900.000:pd.NA,
             999900:pd.NA,
             999.999:pd.NA,
             9999.9:pd.NA,
             99.99999:pd.NA})
)

This returned a data frame with 419,136 rows and 14 columns. The dtypes all appear to have worked correctly, but a closer look shows that they didn't — because I used pd.NA, which forces a dtype of object. I thus loaded NumPy and replaced all of those missing-value representations with np.nan — forcing those columns to be floats, rather than ints. That's not as efficient as ints, but far better than object:

import numpy as np

df = (
    pd
        .read_fwf(filename,
                  colspecs=[(0, 4),  # I4
                         (4, 8),   # I4
                         (8, 11),  # I3
                         (11, 18), # F7.2
                          (18, 25), # F7.1
                          (25, 32), # F7.1
                          (32, 40), # F8.3
                          (40, 47),  # F7.1
                          (47, 56),  # F9.5
                          (56, 65), # F9.0
                          (65, 75), # 10.3
                          (75, 85), # 10.3
                          (85, 93)  # F8.3
                         ],
                header=None, 
                names=['Year', 'DOY', 'Hour', 'Radial Distance',
                      'Lat Angle', 'Long Angle', 'Scalar B magnitude',
                      'Plasma speed', 'SW density fit', 'Temperature from fit',
                      'LECP', 'CRS', 'Bscalar_ERR'],
                )
    .assign(timestamp = lambda df_: pd.to_datetime(df_['Year'].astype(str), format='%Y')
              + pd.to_timedelta(df_['DOY'] - 1, unit='D')
              + pd.to_timedelta(df_['Hour'], unit='h'))
    .replace({9999999:np.nan,
             999900.000:np.nan,
             999900:np.nan,
             999.999:np.nan,
             9999.9:np.nan,
             99.99999:np.nan})
)

The distance is measured in AU (astronomical units), aka the average distance between Earth and the sun. This data is taken from the sun, so it's not precisely the same as saying, "how far is Voyager from Earth," but it's pretty close. Each AU is approximately 0.00578 light days. Convert the measurements to light days, and plot both the mean distance (in light days) and the mean latitude angle for each month of data. Do any dates stick out?

Here is the code I wrote:


au_to_light_days = 0.00578

(
    df
    .select('timestamp', 'Lat Angle',
           light_days = pd.col('Radial Distance') * 0.00578)
    .set_index('timestamp')
    .resample('1ME').mean()
    .pipe(px.line)
)

Notice:

You can see that the measures are wildly different. Voyager made it from 0 AU to just under 1 AU in all of these years, so the line nearly looks flat.

The blue line shows Voyager 1's angle – and we can see that it headed in one direction, and then spend much of the late 1970s and early 1980s turning around before it made a right turn (more or less) in 1985 or so. What was going on?

Well, Voyager 1 flew by Saturn's moon Titan in November 1980. You can read about it at https://www.nasa.gov/history/45-years-ago-voyager-1-begins-its-epic-journey-to-the-outer-planets-and-beyond/, in an amazing article that details what they did.

What about the other turn? Well, the article says cameras were turned off on February 14, 1990 in order to conserve power, as Voyager began to make its way out of the solar system – which is pretty closely aligned with the plot we see here.