[英]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:我的原始数据结构是 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
How can I better write the code to get my desired output?我怎样才能更好地编写代码以获得我想要的输出? I can only use python for this.
我只能为此使用python。
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或 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}]'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.