【问题标题】:Convert dataframe to json including index column将数据框转换为 json,包括索引列
【发布时间】:2022-01-05 02:02:16
【问题描述】:

这听起来是一个简单的问题,但我没有在 json 文件中得到我想要的输出。

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

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

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

我正在尝试使用 to_json 将这些数据框列转换为 json 文件。但是虽然我使用了 orient,但它并没有给我在 json 文件中的索引列。

我的代码:

#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)

输出

{'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}]

【问题讨论】:

    标签: python json python-3.x dataframe


    【解决方案1】:

    pandas DataFrame 具有将index 转换为column 的功能。是.reset_index()

    如果你在.to_json()中用orient='records'这个函数,那么你就可以解决了。

    这是我的解决方案。

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

    【讨论】:

    • 使用 rest_index 给了我日期时间,但不是原来的。它给了我 1637679600000 之类的信息。如何在不更改索引的情况下从索引中获取原始日期?索引列包含这样的日期时间:'2021-06-01 09:00:00'。
    • 我认为您的索引类型(日期时间)是pd.DatetimeIndex 类型。所以你可以使用.strftime() 函数。在这种情况下,首先使用此代码anomalies.index = anomalies.index.strftime('%Y-%m-%d %H:%M:%S')。然后使用我的解决方案。
    • 谢谢,很有帮助。我错过了我们转换日期和时间的部分。
    猜你喜欢
    • 2020-07-11
    • 2017-03-22
    • 1970-01-01
    • 2016-02-14
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2023-04-03
    • 2020-05-15
    相关资源
    最近更新 更多