Skip to content

Instantly share code, notes, and snippets.

@ameliagreenhall
Forked from mikedewar/df2json.py
Last active December 12, 2015 03:39
Show Gist options
  • Save ameliagreenhall/4708719 to your computer and use it in GitHub Desktop.
Save ameliagreenhall/4708719 to your computer and use it in GitHub Desktop.
Convert a pandas dataframe to a json blob
"""
tiny script to convert a pandas data frame into a JSON object
orig: https://gist.github.com/1486027 via Mike Dewar
Test data:
df = pandas.DataFrame({
"time" : [1,2,3,4,5],
"temp" : np.random.rand(5)
})
"""
import json as json
def to_json(df,filename):
d = [
dict([
(colname, row[i])
for i,colname in enumerate(df.columns)
])
for row in df.values
]
return json.dump(d, open(filename + '.json', 'w'))
to_json(df, 'my_filename')
# Preview file:
!head my_filename.json
@ameliagreenhall
Copy link
Author

Assumes you are in an ipython notebook with pandas already imported.

@joelotz
Copy link

joelotz commented May 8, 2013

Why does this assume you are in an ipython notebook? Seems like it is agnostic to both ipython and notebook :-)

@Prooffreader
Copy link

The last line will only work in an ipython notebook. The rest is agnostic.

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