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!
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With