如何将Azure multi-variate anomaly detection输出保存为指定格式CSV文件
实现方法
你可以选择以下两种方案实现,均兼容你当前的Azure多元异常检测结果返回结构:
方案1:使用Python内置csv模块(无需额外安装依赖)
直接调用Python标准库完成写入,代码示例如下:
import csv # 定义CSV表头,和你需要的字段顺序完全匹配 headers = ["timestamp", "is anomaly", "severity", "score", "contributors"] # 打开文件写入 with open("anomaly_detection_result.csv", "w", newline="", encoding="utf-8") as f: writer = csv.writer(f) # 写入表头 writer.writerow(headers) # 循环写入每条检测结果 for r in result.results: # 格式化timestamp为你要求的年,月,日,时,分格式,若timestamp本身已是字符串可直接使用 ts = r.timestamp formatted_ts = f"{ts.year}, {ts.month}, {ts.day}, {ts.hour}, {ts.minute}" # 按顺序写入对应字段 writer.writerow([ formatted_ts, r.value.is_anomaly, r.value.severity, r.value.score, r.value.contributors if r.value.contributors else "None" ])
方案2:使用pandas实现(代码更简洁,适合后续数据处理)
如果你的环境已经安装pandas,可以用更精简的代码完成:
import pandas as pd # 先把所有结果整理为字典列表 data = [] for r in result.results: ts = r.timestamp formatted_ts = f"{ts.year}, {ts.month}, {ts.day}, {ts.hour}, {ts.minute}" data.append({ "timestamp": formatted_ts, "is anomaly": r.value.is_anomaly, "severity": r.value.severity, "score": r.value.score, "contributors": r.value.contributors if r.value.contributors else "None" }) # 转DataFrame后直接导出为CSV df = pd.DataFrame(data) df.to_csv("anomaly_detection_result.csv", index=False, encoding="utf-8")
补充说明
如果你的r.timestamp本身已经是字符串格式,直接替换代码里的formatted_ts为r.timestamp即可,无需额外格式化。
内容的提问来源于stack exchange,提问作者Amzzz
相关产品推荐
相关产品推荐

