簡體   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