繁体   English   中英

将结果转换为对象数组 - Python

[英]Converting result to an array of objects - Python

嗨,我有以下代码

res = df1.loc[df1['Key1'].eq('my_filter_string')]\
    .groupby('Date')['Value'].sum()\
    .reindex(df1['Date'].unique()).fillna(0)
json0bj = res.to_json()
print(json0bj)

这会给我一个输出:

{"2019-09-01":1234.5,"2019-10-01":1345.2}

但是,我想获得一组对象,其输出如下:

[
  {
    "Date": "2019-09-01"
    "Value": 1234.5
  },
  {
    "Date": "2019-10-01"
    "Value": 1345.2
  },
]

我的原始数据结构是 csv 格式,我已经使用 Pandas 阅读过:

Date, Key1, Value
2019-09-01, my_filter_string, 450.5
2019-09-01, my_filter_string, 234.0
2019-10-01, my_filter_string, 500.0
2019-10-01, my_filter_string, 500.0
2019-09-01, my_filter_string, 550.0
2019-10-01, my_filter_string, 345.2
2019-10-01, not_filter_string, 500.0
2019-10-01, not_filter_string, 500.0
2019-09-01, not_filter_string, 550.0
2019-10-01, not_filter_string, 345.2

我怎样才能更好地编写代码以获得我想要的输出? 我只能为此使用python。

提前致谢!

import json

a = {"2019-09-01": 1234.5, "2019-10-01": 1345.2}
b = [
    {
        'Date': k,
        'Value': v
    }
    for k, v in a.items()
]

print(json.dumps(b, indent=4))

输出:

[
    {
        "Date": "2019-09-01",
        "Value": 1234.5
    },
    {
        "Date": "2019-10-01",
        "Value": 1345.2
    }
]

这将为您提供所需的输出:

import pandas as pd
pd.DataFrame(df1.loc[df1['Key1'].eq('my_filter_string')].groupby('Date')['Value'].sum().reindex(df1['Date'].unique()).fillna(0)).reset_index().to_dict(orient='records')   

输出:

[{'Date': '2019-09-01', 'Value': 1234.5},
 {'Date': '2019-10-01', 'Value': 1345.2}]

或 json

 pd.DataFrame(df1.loc[df1['Key1'].eq('my_filter_string')].groupby('Date')['Value'].sum().reindex(df1['Date'].unique()).fillna(0)).reset_index().to_json(orient='records')  

输出:

'[{"Date":"2019-09-01","Value":1234.5},{"Date":"2019-10-01","Value":1345.2}]'

暂无
暂无

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

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