Skip to content

Instantly share code, notes, and snippets.

@ameliagreenhall
Forked from mikedewar/df2json.py
Last active December 12, 2015 03:39

Revisions

  1. ameliagreenhall revised this gist Feb 4, 2013. 1 changed file with 20 additions and 12 deletions.
    32 changes: 20 additions & 12 deletions df2json.py
    Original file line number Diff line number Diff line change
    @@ -1,21 +1,29 @@
    """
    tiny script to convert a pandas data frame into a JSON object
    """
    orig: https://gist.github.com/1486027 via Mike Dewar
    import ujson as json
    import pandas
    import numpy as np
    Test data:
    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)
    """

    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
  2. @mikedewar mikedewar revised this gist Jan 18, 2012. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion df2json.py
    Original file line number Diff line number Diff line change
    @@ -2,7 +2,7 @@
    tiny script to convert a pandas data frame into a JSON object
    """

    import json
    import ujson as json
    import pandas
    import numpy as np

  3. @mikedewar mikedewar created this gist Dec 16, 2011.
    21 changes: 21 additions & 0 deletions df2json.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,21 @@
    """
    tiny script to convert a pandas data frame into a JSON object
    """

    import 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)