I have this numpy 2x10 vector
data = np.ones((10,2)
I would like to make a JSON string with this format:
[{
"times":"2022-11-10 00:00:00",
"values": {
"first": <values of the 1st row>,
"second": <values of the 2nd row>,
}
}
]
What I have done up to now:
dft = pd.DataFrame(data,columns=["first","second"],
index=pd.date_range(start_date, periods=len(data), freq=f"15T")
)
dft.reset_index(inplace=True)
dft = dft.rename(columns={'index': 'times'})
out = dft.to_json(orient='records')
And what I get is:
[{"times":1357041600000,"first":0.0,"second":0.0},{"times":1357042500000,"first":0.0,"second":0.0},{"times":1357043400000,"first":0.0,"second":0.0},{"times":1357044300000,"first":0.0,"second":0.0},{"times":1357045200000,"first":0.0,"second":0.0},{"times":1357046100000,"first":0.0,"second":0.0},{"times":1357047000000,"first":0.0,"second":0.0},{"times":1357047900000,"first":0.0,"second":0.0},{"times":1357048800000,"first":0.0,"second":0.0},{"times":1357049700000,"first":0.0,"second":0.0}]
How can introduce 1) the "values" field as per specification and 2) cast the column times to datetime? Regards!
CodePudding user response:
No need for a DataFrame here, a simple list comprehension will be easier:
import json
start_date = '2022-11-10'
dates = pd.date_range(start_date, periods=len(data), freq=f"15T")
out = [json.dumps({"times":"2022-11-10 00:00:00",
"values": {"first": a, "second": b}}
) for time, (a, b) in zip(dates, data)
]
Output:
['{"times": "2022-11-10 00:00:00", "values": {"first": 1.0, "second": 1.0}}',
'{"times": "2022-11-10 00:00:00", "values": {"first": 1.0, "second": 1.0}}',
'{"times": "2022-11-10 00:00:00", "values": {"first": 1.0, "second": 1.0}}',
'{"times": "2022-11-10 00:00:00", "values": {"first": 1.0, "second": 1.0}}',
'{"times": "2022-11-10 00:00:00", "values": {"first": 1.0, "second": 1.0}}',
'{"times": "2022-11-10 00:00:00", "values": {"first": 1.0, "second": 1.0}}',
'{"times": "2022-11-10 00:00:00", "values": {"first": 1.0, "second": 1.0}}',
'{"times": "2022-11-10 00:00:00", "values": {"first": 1.0, "second": 1.0}}',
'{"times": "2022-11-10 00:00:00", "values": {"first": 1.0, "second": 1.0}}',
'{"times": "2022-11-10 00:00:00", "values": {"first": 1.0, "second": 1.0}}']