簡體   English   中英

無法將 pandas.Series 轉換為 dtype=np.float64 的 numpy.array

[英]can't convert a pandas.Series to a numpy.array with dtype=np.float64

我必須將 pandas 系列轉換為 dtype=float64 的 NumPy 數組,這是引發錯誤的代碼:

series = pd.Series( [np.random.randn(5), np.random.randn(5), np.random.randn(5), np.random.randn(5)])

res = series.to_numpy()
res.astype(np.float64)

這是我得到的錯誤:

----> 3 res.astype(np.float64)

ValueError: setting an array element with a sequence.

我想了解為什么這會引發錯誤,有沒有辦法解決這個問題?

您有一系列列表,無法轉換為單個浮點數。 嘗試:

res = np.array(series.to_list(), dtype=np.float64)

使用純numpy是否適合您,而將pandas.Series排除在外? 最終結果和轉換 arrays -> 系列 -> arrays 是相同的。

例子:

np.hstack([np.random.randn(5), 
           np.random.randn(5), 
           np.random.randn(5), 
           np.random.randn(5)]).reshape(4, -1)

Output:

array([[-1.04567727,  1.10871164, -0.00289682, -1.46394996, -1.6533185 ],
       [-0.27568511, -1.14668944, -0.86748842,  1.49770095,  1.73787835],
       [-0.92369818,  0.10933332, -0.14575781, -0.74659525, -0.84642341],
       [ 0.43899992,  0.93004048, -1.11173766,  0.25189761, -0.66619674]])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM