Convert dataframe to json.

I often use PANDAS for data analysis.
PANDAS can handle data set as DataFrame like R language.
It’s quite useful ;-).
Today, I think about new web app. And I want to use MongoDB for data strage.
MongoDB is No SQL database, and data format looks like Json.
So, I want to convert Pandas DataFrame object to json format.
Fortunately PANDAS has to_json method that convert DataFrame to json!
I tested the function.

I want to data by each rows.
I set orient option was ‘index’ because default to_json function handle data each columns.

Like this.

import pandas as pd
df = pd.read_csv('sample_mmps_default.csv', header=None)
df.columns = ['mol1', 'mol2', 'id1', 'id2', 'trans', 'context']
jsondf = df.to_json( orient='index')

Now I could get json format each rows.
I uploaded code snippet.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s