我已经对结果集进行了分组,并尝试使用to_json方法将结果转换为python。
这是我将结果转换为json的代码。结果变量包含所有结果。
results = {'main_category' : {'total_count' : total_count,'total_predicted_postive_count' : total_predicted_postive_count, 'total_predicted_negative_count' : total_predicted_negative_count ,
'total_predicted_postive_rate' : total_predicted_postive_rate, 'total_predicted_negative_rate' : total_predicted_negative_rate, 'high_predicted_positive_region' : high_predicted_positive_region,
'model_accuracy' : model_accuracy } }, { 'category' : [{ 'subcategory' : 'gender'}, [{'subcategory_name' : [{ 'subcategory_name' : 'male', 'churn_count' : male_churn_count, 'churn_rate' : male_churn_rate, 'retention_count' : male_retention_count,
'retention_rate' : male_retention_rate }] }] ] }
overall_results = pd.Series(results).to_json(orient='records')
print(overall_results)
在我将其转换为json之后,我的输出将是这样的
[
{
"main_category": {
"high_predicted_positive_region": 564,
"total_predicted_postive_count": 1481,
"model_accuracy": 1,
"total_predicted_postive_rate": 0.2212429041,
"total_predicted_negative_rate": 0.7787570959,
"total_count": 7032,
"total_predicted_negative_count": 5213
}
},
{
"category": [
{
"subcategory": "gender"
},
[
{
"subcategory_name": [
{
"churn_rate": 0.106363908,
"churn_count": 712,
"retention_count": 2658,
"subcategory_name": "male",
"retention_rate": 0.3970720048
}
]
}
]
]
}
]
但是我的预期输出格式应该是这样的
[
{
"main_category": {
"high_predicted_positive_region": 564,
"total_predicted_postive_count": 1481,
"model_accuracy": 1,
"total_predicted_postive_rate": 0.2212429041,
"total_predicted_negative_rate": 0.7787570959,
"total_count": 7032,
"total_predicted_negative_count": 5213
}
},
{
"category": [
{
"subcategory": "gender"
},
[
{
"subcategory_name": [
{
"subcategory_name": "male",
"churn_count": 712,
"churn_rate": 0.106363908,
"retention_count": 2658,
"retention_rate": 0.3970720048
}
]
}
]
]
}
]
在子类别名称数组中,无论我在结果中提到什么顺序,都应该显示。但我的情况好坏参半。
我应该根据该订单在哪里更改。任何其他方式来获得相同的结果格式。
答案 0 :(得分:1)
在Python中,字典不是有序的。如果要保留广告订单,则需要使用OrderedDict。
您似乎正在使用Pandas。我对此并不了解,但this topic将帮助您在Pandas中使用OrderedDicts。
答案 1 :(得分:0)
json.dumps()有一个排序键,当设置为True时,将输出一个已排序的json输出。 您可以使用sorted = True插入json.dumps()调用。 (不确定orient ='记录'会做什么,但你会失去这个。)
请注意,这不会在python3上作为混合模式<操作员已被删除,如果您的密钥有不同的类型,您将收到错误。
一般来说,dicts是无序的......
否则你必须编写自己的dict解析器....