Created
July 18, 2017 07:54
-
-
Save akiross/dbccc848827b08a23f4fd5a78b0ff951 to your computer and use it in GitHub Desktop.
Simple example on using dates as index
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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