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