Skip to content

Instantly share code, notes, and snippets.

@JackStouffer
Created December 22, 2014 16:03
Show Gist options
  • Save JackStouffer/d59f52449def9b190d6e to your computer and use it in GitHub Desktop.
Save JackStouffer/d59f52449def9b190d6e to your computer and use it in GitHub Desktop.
Get Data Grouped By Month in Pandas
import pandas
import numpy
def resampled_data(query, date_col, target_col, period="M"):
""" Function that takes an sql query and returns the sum of a target column
by a period. Useful for getting monthly data
"""
df = pandas.read_sql(query, conn)
df.set_index(df[date_col], inplace=True)
df.index = pandas.to_datetime(df.index)
data = df[target_col].resample(period, how='sum').values
data = data[~numpy.isnan(data)]
return data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment