Writing the post that I wished I'd found when I started learning whatever it was...

Creating a time series from existing data in pandas

Posted on 9 May 2017 in Python, TIL

pandas is a high-performance library for data analysis in Python. It's generally excellent, but if you're a beginner or you use it rarely, it can be tricky to find out how to do quite simple things -- the code to do what you want is likely to be very clear once you work it out, but working it out can be relatively hard.

A case in point, which I'm posting here largely so that I can find it again next time I need to do the same thing... I had a list start_times of dictionaries, each of which had (amongst other properties) a timestamp and a value. I wanted to create a pandas time series object to represent those values.

The code to do that is this:

import pandas as pd
series = pd.Series(
    [cs["value"] for cs in start_times],
    index=pd.DatetimeIndex([cs["timestamp"] for cs in start_times])
)

Perfectly clear once you see it, but it did take upwards of 40 Google searches and help from two colleagues with a reasonable amount of pandas experience to work out what it should be.

Citing this post

This is a blog, and if you want to link to this post then please do :-) However, if you're writing something more academic and need to do a proper citation, then here's a BibTeX block to make things easier.

@misc{thomas2017may-creating-a-time-series-from-existing-data-in-pandas,
  author       = {Thomas, Giles},
  title        = {{Creating a time series from existing data in pandas}},
  year         = {2017},
  month        = may,
  howpublished = {Blog post},
  url          = {https://www.gilesthomas.com/2017/05/creating-a-time-series-from-existing-data-in-pandas},
}