Skip to content

Instantly share code, notes, and snippets.

@arsenyinfo
Created January 17, 2017 15:30
Show Gist options
  • Save arsenyinfo/a29a76d60f107367e7c64982ff26263d to your computer and use it in GitHub Desktop.
Save arsenyinfo/a29a76d60f107367e7c64982ff26263d to your computer and use it in GitHub Desktop.
Convert pandas DataFrame to Prometheus (https://prometheus.io) text format
from datetime import datetime
from itertools import product
from random import randint
import pandas as pd
def generate_df():
# just example
index = pd.date_range('2017-01-01', datetime.now(), freq='H')
req_types = ('GET', 'POST')
codes = ('404', '302', '200')
data = [{'ts': ts, 'req_type': req_type, 'code': code, 'value': randint(0, 10)}
for ts, req_type, code in product(index, req_types, codes)]
return pd.DataFrame(data)
def convert(df, metric_name='arsenys_awesome_metric', labels=('code', 'req_type'), ):
for _, row in df.iterrows():
params = ','.join(['{}=\"{}\"'.format(label, row.get(label)) for label in labels])
if params:
line = '{}{{{}}}\t'.format(metric_name, params)
else:
line = '{}\t'
unix_time = int((row.get('ts') - datetime(1970, 1, 1)).total_seconds()) * 1000
line = '{}{}\t{}'.format(line, row.get('value'), unix_time)
print(line)
if __name__ == '__main__':
convert(generate_df())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment