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

时间:2019-12-16 04:02:56

标签: python json pandas

嗨,我有以下代码

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格式,我已经使用熊猫阅读过:

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。

谢谢!

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

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

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