Skip to content

Instantly share code, notes, and snippets.

@akiross
Created July 18, 2017 07:54
Show Gist options
  • Save akiross/dbccc848827b08a23f4fd5a78b0ff951 to your computer and use it in GitHub Desktop.
Save akiross/dbccc848827b08a23f4fd5a78b0ff951 to your computer and use it in GitHub Desktop.
Simple example on using dates as index
#!/usr/bin/env python3
import pandas as pd
import io
# Make up some data
example_csv = '''Birthday,Name,Surname
1643-01-04,Isaac,Newton
1879-03-14,Albert,Einsten
1942-01-08,Stephen,Hawking
1564-02-15,Galileo,Galilei
1777-04-30,Carl Friedrich,Gauss
1815-12-10,Ada,Lovelace
1791-12-26,Charles,Babbage'''
df = pd.read_csv(
io.StringIO(example_csv), # Use a string like a file
parse_dates=True, # Tell pandas to parse (all) the dates
)
print(df) # Let's see original data
# Natural numbers used as index
print(df.index.values)
# You can slice using index
print(df[2:4])
# Set birthday as index
df.set_index('Birthday', inplace=True)
# Sort it to make it accessible
df.sort_index(inplace=True)
# Data is now indexed by date
print(df)
# You can conveniently slice by time
print(df['1700':'1800'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment