Skip to content
Advertisement

Pandas row to json

I have a dataframe in pandas and my goal is to write each row of the dataframe as a new json file.

I’m a bit stuck right now. My intuition was to iterate over the rows of the dataframe (using df.iterrows) and use json.dumps to dump the file but to no avail.

Any thoughts?

Advertisement

Answer

Pandas DataFrames have a to_json method that will do it for you: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_json.html

If you want each row in its own file you can iterate over the index (and use the index to help name them):

for i in df.index:
    df.loc[i].to_json("row{}.json".format(i))
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement