0

My original output will looks like this

quarterly_churn_count["Churn"]
Out[35]: 
year  quarter
2008  1          1070
2013  1            31
      2            47
      3            57
      4            59
2014  1            33
      2            43
      3            49
      4            37
Name: Churn, dtype: int64

I am using this below code to convert to json format

results = [{'quarterly_churn_count["Churn"]' : quarterly_churn_count["Churn"] }]
final = pd.DataFrame(results)
final = final.to_json(orient='records')
print(final)

My output will be like this after converting to json

[
    {
        "quarterly_churn_count[\"Churn\"]": [
            1070,
            31,
            47,
            57,
            59,
            33,
            43,
            49,
            37
        ]
    }
]

I am not able to get the key like year, quarter. I am getting only values after converting that to to_json with orient value records.

My expected results would be like this, for example

quarter[
{
year : 2008
quarter : 1
value :518
}
{
year :1999
quarter : 4
value : 89
}
]

1 Answers1

1

I think need:

j = (quarterly_churn_count['Churn'].reset_index()
                                   .rename(columns={'Churn':'value'})
                                   .to_json(orient='records'))
print (j)

[{"year":2008,"quarter":1,"Churn":1070},
 {"year":2013,"quarter":1,"Churn":31},
 {"year":2013,"quarter":2,"Churn":47},
 {"year":2013,"quarter":3,"Churn":57},
 {"year":2013,"quarter":4,"Churn":59},
 {"year":2014,"quarter":1,"Churn":33},
 {"year":2014,"quarter":2,"Churn":43},
 {"year":2014,"quarter":3,"Churn":49},
 {"year":2014,"quarter":4,"Churn":37}]

EDIT:

import pandas as pd
import json

quarterly_churn_count = pd.DataFrame({'Churn': {(2013, 1): 31, (2014, 1): 33, (2014, 3): 49, (2013, 2): 47, (2013, 3): 57, (2008, 1): 1070, (2014, 4): 37, (2013, 4): 59, (2014, 2): 43}})
quarterly_churn_count.index.names = ['year', 'quarter']
print (quarterly_churn_count)

quarterly_retention_count = quarterly_churn_count * 100

j = (pd.concat([quarterly_churn_count["Churn"], quarterly_retention_count["Churn"]])
       .reset_index()
       .rename(columns={'Churn':'value'})
       .to_json(orient='records'))
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252