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.
https://github.com/iwatobipen/mishimasyk/blob/master/df2json_sample.ipynb

Published by iwatobipen

I'm medicinal chemist in mid size of pharmaceutical company. I love chemoinfo, cording, organic synthesis, my family.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: