简体   繁体   中英

Converting result to an array of objects - Python

Hi I have the following code

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)

Which will give me an output:

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

However, I would like to get an array of objects with the out put like:

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

My original data structure is in csv format which I have already read using 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

How can I better write the code to get my desired output? I can only use python for this.

Thanks in advance!

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

outputs:

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

This will give you the output your looking for:

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

output:

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

or 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')  

output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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