繁体   English   中英

将 dataframe 转换为 json 包括索引列

[英]convert dataframe to json including index column

这听起来很简单,但我在 json 文件中没有得到我想要的 output。

在获得异常检测器的结果后,我正在尝试将 dataframe 转换为 json。

数据框包含以下列,包括索引列作为日期时间。

index column - datetime,
loss,
rolling_mean,
exponential_mean
static_threshold, 
dynamic_threshold, 
anomlay,
global anomaly,
total value

我正在尝试使用to_json将这些 dataframe 列转换为 json 文件。但它没有给我 json 文件中的索引列,尽管我使用了orient

我的代码:

#anomalies is a dataframe which has all the above columns

result = anomalies.to_json(orient='index')
parsed = json.loads(result)
json.dumps(parsed, indent=4)
print(parsed)  
#print(result)

output

{'1637593200000': {'loss': 0.2777269163, 
                   'rolling_mean': 0.3497074445,  
                   'exp_mean': 0.2994830801, 
                   'static_threshold': 0.2707094526, 
                   'dynamic_threshold': 0.3497074445, 
                   'global_anomaly': False, 
                   'anomaly': True, 
                   'total': 0.2090592334}, 
'1637596800000': {'loss': 0.2816397219, 
                  'rolling_mean': 0.3550902968, 
                  'exp_mean': 0.3079049915, 
                  'static_threshold': 0.2707094526, 
                  'dynamic_threshold': 0.3550902968, 
                  'global_anomaly': False, 
                  'anomaly': True, 
                  'total': 0.0818815331}}

我想要的是:

[{'datetime':20220105,
  'loss': 0.2777269163, 
  'rolling_mean': 0.3497074445,  
  'exp_mean': 0.2994830801, 
  'static_threshold': 0.2707094526, 
  'dynamic_threshold': 0.3497074445, 
  'global_anomaly': False, 
  'anomaly': True, 
  'total': 0.2090592334}, 
 {'datetime':20220105,
  'loss': 0.2816397219, 
  'rolling_mean': 0.3550902968, 
  'exp_mean': 0.3079049915, 
  'static_threshold': 0.2707094526, 
  'dynamic_threshold': 0.3550902968, 
  'global_anomaly': False, 
  'anomaly': True, 
  'total': 0.0818815331}]

pandas DataFrame 有一个 function 用于将index转换为column 它是.reset_index()

如果您在.to_json()中使用带有orient='records'的 function ,那么您可以解决它。

这是我的解决方案。

result = anomalies.reset_index().to_json(orient='records', indent=4)
print(result)  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM