-
-
Save ameliagreenhall/4708719 to your computer and use it in GitHub Desktop.
Convert a pandas dataframe to a json blob
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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 |
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
Why does this assume you are in an ipython notebook? Seems like it is agnostic to both ipython and notebook :-)