我的原始输出将如下所示
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
我使用下面的代码转换为json格式
results = [{'quarterly_churn_count["Churn"]' : quarterly_churn_count["Churn"] }]
final = pd.DataFrame(results)
final = final.to_json(orient='records')
print(final)
转换为json后,我的输出将如下所示
[
{
"quarterly_churn_count[\"Churn\"]": [
1070,
31,
47,
57,
59,
33,
43,
49,
37
]
}
]
我无法像年,季度那样获得密钥。在使用东方值记录将其转换为to_json之后,我只获得了值。
我的预期结果将是这样的,例如
quarter[
{
year : 2008
quarter : 1
value :518
}
{
year :1999
quarter : 4
value : 89
}
]
答案 0 :(得分:1)
我认为需要:
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}]
编辑:
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'))