Pandas Dataframe To Json With Multiple Nested Categories
I'm looking for a solution to convert a Pandas DataFrame with 3 subcategories to an JSON output without any lists. This is the data-structure I got: import pandas as pd df = pd.Da
Solution 1:
Credit to DSM but I modified the .ix
to .iloc
def recur_dictify(frame):
if len(frame.columns) == 1:
if frame.values.size == 1: return frame.values[0][0]
return frame.values.squeeze()
grouped = frame.groupby(frame.columns[0])
d = {k: recur_dictify(g.iloc[:,1:]) for k,g in grouped}
return d
recur_dictify(df)
Out[211]:
{'A': {'BB': {'CC': {'P1': 132, 'P2': 51}}, 'BC': {'CD': {'P3': 12}}},
'B': {'BB': {'CD': {'P1': 421, 'P4': 55}}},
'C': {'BB': {'CC': {'P1': 11}}, 'BC': {'CD': {'P3': 123}, 'CE': {'P6': 312}}}}
Post a Comment for "Pandas Dataframe To Json With Multiple Nested Categories"