Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataFrame to Json Using First Col as Key and Second as Value

I have a dataframe that looks like this:

k = pd.DataFrame({'A':[1,2,3,4], 'B':['a','b','c','d']})

And I want to insert into a mongoDB looking like this:

dic = {1:'a', 2:'b',3:'c',4:'d'}

How could I do it?

I have checked things like this but they do not seem to work on my df:

convert pandas dataframe to json object - pandas

Thanks in advance!

like image 965
Borja_042 Avatar asked Jun 11 '18 09:06

Borja_042


1 Answers

Use Series.to_json and if necessary change key value add rename:

print (k.set_index('A').rename(columns={'B':'index1'}).to_json())
{"index1":{"1":"a","2":"b","3":"c","4":"d"}}

If need export to file:

k.set_index('A').rename(columns={'B':'index1'}).to_json('file.json')
like image 111
jezrael Avatar answered Sep 18 '22 00:09

jezrael