Reindex and convert to json in pandas

Viewed 327

I have a dataframe:

     accountname ip
0    aa          10.1.1.1
1    bb          10.1.1.2
2    cc          10.1.1.3

I want a json like this:

{ 'aa':{'ip':'10.1.1.1'}, 'bb':{'ip':'10.1.1.2'},'cc':{'ip':'10.1.1.3'}}

But with

df.index.name = 'accountname'
df.reset_index(drop=True)
json = df.to_json(orient='index')

I have old index in json. Any advive would be appreciated.

1 Answers

Here is a simple solution:

import pandas as pd
from io import StringIO

# Sample data
string=u"""accountname,ip
aa,10.1.1.1
bb,10.1.1.2
cc,10.1.1.3"""

# Creates a DataFrame from sample data
df = pd.read_csv(StringIO(string))

# the key here is the T where rows become columns
df.set_index("accountname").T.to_json()
# or
#df.set_index('accountname').to_json(orient='index')

returns:

'{"aa":{"ip":"10.1.1.1"},"bb":{"ip":"10.1.1.2"},"cc":{"ip":"10.1.1.3"}}'
Related