Python can';t将pandas.Series转换为dtype=np.float64的numpy.array

Python can';t将pandas.Series转换为dtype=np.float64的numpy.array,python,pandas,numpy,numpy-ndarray,Python,Pandas,Numpy,Numpy Ndarray,我必须将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) Value

我必须将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
排除在混合之外吗?最终结果与转换数组->系列->数组是相同的

例如:

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

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]])

我只是好奇为什么你首先把数组放在一个系列中,然后再回到数组?我有一个复杂的数据管道,需要这种行为,那里的代码只是为了让成员更容易重现错误。好吧,公平点。刚刚为你提供了另一个解决方案。。。看看这是否是你的一个选择。非常感谢,这一次对我不起作用,但我相信它会在另一天派上用场。谢谢你的回答,你能详细说明我的方法不起作用的原因吗?我已经在回答中解释过了。更详细一点:
res=series.to\u numpy()
是一个numpy 1D对象数组,每个对象都是一个列表,不能转换为float。