我有下面發布的串列,它包含串列,所以它是一個串列串列,我有一個回傳的網路服務return jsonify(resultsDict)。我面臨的問題是當我運行應用程式時,我收到下面發布的任何錯誤訊息。如下面的代碼所示,我嘗試設定dtype=np.float64and dtype=object,但它們中的每一個都會生成一個與之相關的錯誤,如下面的代碼所示。請讓我知道如何解決它
嘗試_1
resultsDict={
"extras": {
"pvTreatment":np.array(pvTreatment,dtype=np.float64).tolist(),
...
...
...
}
}
**error associated**:
ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (7,) inhomogeneous part.
嘗試_2
resultsDict = {
"extras": {
"pvTreatment":np.array(pvTreatment,dtype=object).tolist(),
...
...
...
}
}
**error associated**:
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type float32 is not JSON serializable
uj5u.com熱心網友回復:
如果我嘗試用兩個長度不同的陣列創建一個陣列,我會得到你的錯誤:
In [186]: np.array([np.ones((3)), np.zeros((4))],float)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [186], in <cell line: 1>()
----> 1 np.array([np.ones((3)), np.zeros((4))],float)
ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (2,) inhomogeneous part.
我可以制作一個objectdtype 陣列:
In [187]: np.array([np.ones((3)), np.zeros((4))],object)
Out[187]: array([array([1., 1., 1.]), array([0., 0., 0., 0.])], dtype=object)
但是當我使用時,tolist我得到一個包含兩個陣列的串列:
In [188]: np.array([np.ones((3)), np.zeros((4))],object).tolist()
Out[188]: [array([1., 1., 1.]), array([0., 0., 0., 0.])]
陣列不是 JSON 可序列化的。
如果將內部陣列更改為串列,我們將得到一個串列串列:
In [191]: np.array([np.ones((3)).tolist(), np.zeros((4)).tolist()],object).tolist()
Out[191]: [[1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0]]
對于這種事情,請避免使用陣列 - 外部串列和內部串列。
uj5u.com熱心網友回復:
我的建議是首先使用使串列大小相等(如果它們沒有數量級的差異),如本例所示 - List of lists into numpy array
通過這種方式,您可以更輕松地將其反序列化為串列串列。如果需要,您也可以使用諸如 pickle 之類的外部庫。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/525354.html
上一篇:嘗試遍歷陣列并注釋它們
