Python: How to transform DF into Json series?

Viewed 65

I have the following Dataframe in python:

date(index

And I want to transform it into the the following json object so I can send it to front end and plot it on highcharts:

 name: 'netflix',
  data: [
    [1579996800, 67],
    [1580601600, 70],
    [1581206400, 68],
    [1581811200, 72],
    etc...
  ]
}, {
  name: 'netflix movies',
  data: [
    [1579996800, 59],
    [1580601600, 69],
    [1581206400, 71],
    [1581811200, 63],
    etc...
  ]
}]

Im using:

    json = df.to_json()

But I get something very close but the date it's showing up as an index and not as a value. It's ok that shows timestamp but I want it to be [1579996800, 67] and not [1579996800: 67]

How do I get an JSON Array of objects: [ {x : x value, y: y value}, {x : x value, y: y value}, ...] from this dataframe? So I can send to the front end and plot using highcharts?

enter image description here

If I reset the index then everything gets messy. What would be the best way of achieving this?

1 Answers

Here is a solution using just Python's powerful list comprehension:

import pandas as pd, numpy as np, datetime as dt
now = dt.datetime.now()
r = lambda: np.random.randint(0,100,10)
td = lambda i: now+dt.timedelta(i)
dic = {"date": [td(i) for i in range(10)], "netflix": r(), "Netflix movie": r(),  "Netflix stock": r(),  "Netflix login": r(),  "Netflix party": r(), }
df = pd.DataFrame(dic)

req_json = {col: [[a,b] for a, b in zip(df['date'],df[col])] for col in df.columns[1:]}
Related