Skip to content

Instantly share code, notes, and snippets.

@mikedewar
Created December 16, 2011 13:17
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save mikedewar/1486027 to your computer and use it in GitHub Desktop.
Save mikedewar/1486027 to your computer and use it in GitHub Desktop.
A little script to convert a pandas data frame to a JSON object. Is there a better way?
"""
tiny script to convert a pandas data frame into a JSON object
"""
import ujson as json
import pandas
import numpy as np
df = pandas.DataFrame({
"time" : [1,2,3,4,5],
"temp" : np.random.rand(5)
})
d = [
dict([
(colname, row[i])
for i,colname in enumerate(df.columns)
])
for row in df.values
]
return json.dumps(d)
@justalfred
Copy link

I just found need to do exactly this, except stored as a dict with the row names as keys. For that, I did: dict([(row[0], dict(row[1])) for row in df.iterrows()]). df.iterkv() gets you the transpose of that.

@tponthieux
Copy link

You could also nest a dictionary comprehension.
d = [{colname : row[i] for i, colname in enumerate(df.columns)} for row in df.iterrows()]

@leondutoit
Copy link

This dict comprehension includes only the relevant information:
[{k:df.values[i][v] for v,k in enumerate(df.columns)} for i in range(len(df)) ]

@lrq3000
Copy link

lrq3000 commented Mar 28, 2013

A related pull request:
pandas-dev/pandas#1263

@asmedrano
Copy link

Looks like thats comming in the next version.
http://pandas.pydata.org/pandas-docs/dev/io.html#writing-json

@agconti
Copy link

agconti commented Sep 9, 2013

To complete the thread: Convert DataFrame to JSON with pandas.io.

@streamnsight
Copy link

and now since a little while just use:
df.to_json()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment