【问题标题】:can't convert a pandas.Series to a numpy.array with dtype=np.float64无法将 pandas.Series 转换为 dtype=np.float64 的 numpy.array
【发布时间】:2021-03-10 15:10:22
【问题描述】:

我必须将 pandas Series 转换为 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.

我想了解为什么这会引发错误,有没有办法解决这个问题?

【问题讨论】:

  • 只是好奇为什么你首先将数组放在一个系列中,只是为了回到数组?
  • 我有一个复杂的数据管道,需要这种行为,那里的代码只是为了让成员更容易重现错误。
  • 好的,公平点。刚刚为您弹出了一个替代解决方案......看看这是否适合您。
  • 非常感谢,这一次对我不起作用,但我相信改天会派上用场的。

标签: python pandas numpy numpy-ndarray


【解决方案1】:

您有一系列列表,无法转换为单个浮点数。试试:

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

【讨论】:

  • 感谢您的回答,能否请您详细说明为什么我的方法不起作用?
  • 我已经在回答中解释过了。更多细节:res = series.to_numpy() 是一个 numpy 一维对象数组,每个都是一个列表,不能转换为浮点数。
【解决方案2】:

您会选择使用纯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]])

【讨论】:

    猜你喜欢
    • 2021-06-01
    • 2014-11-15
    • 2017-08-24
    • 2018-06-11
    相关资源
    最近更新 更多