Pandas multiindex to json









up vote
1
down vote

favorite












I have a dataframe as below



 name address.office.street address.office.city address.office.country address.office.postcode location.tracker.id
0 Name1 Street1 City1 Country1 100 9,99,02,129
1 Name2 Street2 City2 Country2 200 1,91,95,129
2 Name3 Street3 City3 Country3 300 99,90,259


I split the column and created MultiIndex as below



idx = df.columns.str.split('.', expand=True)
df.columns = idx
df[('location', 'tracker', 'id')] = df[('location', 'tracker', 'id')].str.split(',')
print(df)


name address location
NaN office tracker
NaN street city country postcode id
0 Name1 Street1 City1 Country1 100 [9, 99, 02, 129]
1 Name2 Street2 City2 Country2 200 [1, 91, 95, 129]
2 Name3 Street3 City3 Country3 300 [99, 90, 259]


I want to convert this to nested json. May I know the pandas way to convert this into below json.




[
"name": "Name1",
"address":
"office":
"street": "Street1",
"city": "City1",
"country": "Country1",
"postcode": 100

,
"location":
"tracker":
"id": [
"9",
"99",
"02",
"129"
]

,
"name": "Name2",
"address":
"office":
"street": "Street2",
"city": "City2",
"country": "Country2",
"postcode": 200

,
"location":
"tracker":
"id": [
"1",
"91",
"95",
"129"
]

,
"name": "Name3",
"address":
"office":
"street": "Street3",
"city": "City3",
"country": "Country3",
"postcode": 300

,
"location":
"tracker":
"id": [
"99",
"90",
"259"
]

]




While I can get the above result with below code, it becomes slow when the number of records(df.shape[0]) are high.



nested_dict = lambda: defaultdict(nested_dict)
result = nested_dict()

result_list =
for cntr in range(df.shape[0]):
for i, j in df.iteritems():
value = j[cntr]
if not pd.isnull(i[2]):
result[i[0]][i[1]][i[2]] = value
elif not pd.isnull(i[1]):
result[i[0]][i[1]] = value
elif not pd.isnull(i[0]):
result[i[0]] = value

result_list.append(deepcopy(result))

print(json.dumps(result_list, indent=4))


I look to simplify this similar to



(df.groupby(level=['level0']).apply(lambda df: df.xs(df.name))).to_json()


But, could not get the results as expected.










share|improve this question























  • I don't think you will find a function to do this, you will probably end up using defaultdicts as you have already tried..
    – Franco Piccolo
    Nov 12 at 6:34














up vote
1
down vote

favorite












I have a dataframe as below



 name address.office.street address.office.city address.office.country address.office.postcode location.tracker.id
0 Name1 Street1 City1 Country1 100 9,99,02,129
1 Name2 Street2 City2 Country2 200 1,91,95,129
2 Name3 Street3 City3 Country3 300 99,90,259


I split the column and created MultiIndex as below



idx = df.columns.str.split('.', expand=True)
df.columns = idx
df[('location', 'tracker', 'id')] = df[('location', 'tracker', 'id')].str.split(',')
print(df)


name address location
NaN office tracker
NaN street city country postcode id
0 Name1 Street1 City1 Country1 100 [9, 99, 02, 129]
1 Name2 Street2 City2 Country2 200 [1, 91, 95, 129]
2 Name3 Street3 City3 Country3 300 [99, 90, 259]


I want to convert this to nested json. May I know the pandas way to convert this into below json.




[
"name": "Name1",
"address":
"office":
"street": "Street1",
"city": "City1",
"country": "Country1",
"postcode": 100

,
"location":
"tracker":
"id": [
"9",
"99",
"02",
"129"
]

,
"name": "Name2",
"address":
"office":
"street": "Street2",
"city": "City2",
"country": "Country2",
"postcode": 200

,
"location":
"tracker":
"id": [
"1",
"91",
"95",
"129"
]

,
"name": "Name3",
"address":
"office":
"street": "Street3",
"city": "City3",
"country": "Country3",
"postcode": 300

,
"location":
"tracker":
"id": [
"99",
"90",
"259"
]

]




While I can get the above result with below code, it becomes slow when the number of records(df.shape[0]) are high.



nested_dict = lambda: defaultdict(nested_dict)
result = nested_dict()

result_list =
for cntr in range(df.shape[0]):
for i, j in df.iteritems():
value = j[cntr]
if not pd.isnull(i[2]):
result[i[0]][i[1]][i[2]] = value
elif not pd.isnull(i[1]):
result[i[0]][i[1]] = value
elif not pd.isnull(i[0]):
result[i[0]] = value

result_list.append(deepcopy(result))

print(json.dumps(result_list, indent=4))


I look to simplify this similar to



(df.groupby(level=['level0']).apply(lambda df: df.xs(df.name))).to_json()


But, could not get the results as expected.










share|improve this question























  • I don't think you will find a function to do this, you will probably end up using defaultdicts as you have already tried..
    – Franco Piccolo
    Nov 12 at 6:34












up vote
1
down vote

favorite









up vote
1
down vote

favorite











I have a dataframe as below



 name address.office.street address.office.city address.office.country address.office.postcode location.tracker.id
0 Name1 Street1 City1 Country1 100 9,99,02,129
1 Name2 Street2 City2 Country2 200 1,91,95,129
2 Name3 Street3 City3 Country3 300 99,90,259


I split the column and created MultiIndex as below



idx = df.columns.str.split('.', expand=True)
df.columns = idx
df[('location', 'tracker', 'id')] = df[('location', 'tracker', 'id')].str.split(',')
print(df)


name address location
NaN office tracker
NaN street city country postcode id
0 Name1 Street1 City1 Country1 100 [9, 99, 02, 129]
1 Name2 Street2 City2 Country2 200 [1, 91, 95, 129]
2 Name3 Street3 City3 Country3 300 [99, 90, 259]


I want to convert this to nested json. May I know the pandas way to convert this into below json.




[
"name": "Name1",
"address":
"office":
"street": "Street1",
"city": "City1",
"country": "Country1",
"postcode": 100

,
"location":
"tracker":
"id": [
"9",
"99",
"02",
"129"
]

,
"name": "Name2",
"address":
"office":
"street": "Street2",
"city": "City2",
"country": "Country2",
"postcode": 200

,
"location":
"tracker":
"id": [
"1",
"91",
"95",
"129"
]

,
"name": "Name3",
"address":
"office":
"street": "Street3",
"city": "City3",
"country": "Country3",
"postcode": 300

,
"location":
"tracker":
"id": [
"99",
"90",
"259"
]

]




While I can get the above result with below code, it becomes slow when the number of records(df.shape[0]) are high.



nested_dict = lambda: defaultdict(nested_dict)
result = nested_dict()

result_list =
for cntr in range(df.shape[0]):
for i, j in df.iteritems():
value = j[cntr]
if not pd.isnull(i[2]):
result[i[0]][i[1]][i[2]] = value
elif not pd.isnull(i[1]):
result[i[0]][i[1]] = value
elif not pd.isnull(i[0]):
result[i[0]] = value

result_list.append(deepcopy(result))

print(json.dumps(result_list, indent=4))


I look to simplify this similar to



(df.groupby(level=['level0']).apply(lambda df: df.xs(df.name))).to_json()


But, could not get the results as expected.










share|improve this question















I have a dataframe as below



 name address.office.street address.office.city address.office.country address.office.postcode location.tracker.id
0 Name1 Street1 City1 Country1 100 9,99,02,129
1 Name2 Street2 City2 Country2 200 1,91,95,129
2 Name3 Street3 City3 Country3 300 99,90,259


I split the column and created MultiIndex as below



idx = df.columns.str.split('.', expand=True)
df.columns = idx
df[('location', 'tracker', 'id')] = df[('location', 'tracker', 'id')].str.split(',')
print(df)


name address location
NaN office tracker
NaN street city country postcode id
0 Name1 Street1 City1 Country1 100 [9, 99, 02, 129]
1 Name2 Street2 City2 Country2 200 [1, 91, 95, 129]
2 Name3 Street3 City3 Country3 300 [99, 90, 259]


I want to convert this to nested json. May I know the pandas way to convert this into below json.




[
"name": "Name1",
"address":
"office":
"street": "Street1",
"city": "City1",
"country": "Country1",
"postcode": 100

,
"location":
"tracker":
"id": [
"9",
"99",
"02",
"129"
]

,
"name": "Name2",
"address":
"office":
"street": "Street2",
"city": "City2",
"country": "Country2",
"postcode": 200

,
"location":
"tracker":
"id": [
"1",
"91",
"95",
"129"
]

,
"name": "Name3",
"address":
"office":
"street": "Street3",
"city": "City3",
"country": "Country3",
"postcode": 300

,
"location":
"tracker":
"id": [
"99",
"90",
"259"
]

]




While I can get the above result with below code, it becomes slow when the number of records(df.shape[0]) are high.



nested_dict = lambda: defaultdict(nested_dict)
result = nested_dict()

result_list =
for cntr in range(df.shape[0]):
for i, j in df.iteritems():
value = j[cntr]
if not pd.isnull(i[2]):
result[i[0]][i[1]][i[2]] = value
elif not pd.isnull(i[1]):
result[i[0]][i[1]] = value
elif not pd.isnull(i[0]):
result[i[0]] = value

result_list.append(deepcopy(result))

print(json.dumps(result_list, indent=4))


I look to simplify this similar to



(df.groupby(level=['level0']).apply(lambda df: df.xs(df.name))).to_json()


But, could not get the results as expected.







python python-3.x pandas pandas-groupby multi-index






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 12 at 4:51

























asked Nov 10 at 6:32









user3665224

3061316




3061316











  • I don't think you will find a function to do this, you will probably end up using defaultdicts as you have already tried..
    – Franco Piccolo
    Nov 12 at 6:34
















  • I don't think you will find a function to do this, you will probably end up using defaultdicts as you have already tried..
    – Franco Piccolo
    Nov 12 at 6:34















I don't think you will find a function to do this, you will probably end up using defaultdicts as you have already tried..
– Franco Piccolo
Nov 12 at 6:34




I don't think you will find a function to do this, you will probably end up using defaultdicts as you have already tried..
– Franco Piccolo
Nov 12 at 6:34

















active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53236568%2fpandas-multiindex-to-json%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown






























active

oldest

votes













active

oldest

votes









active

oldest

votes






active

oldest

votes















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53236568%2fpandas-multiindex-to-json%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Top Tejano songwriter Luis Silva dead of heart attack at 64

ReactJS Fetched API data displays live - need Data displayed static

政党