【发布时间】:2022-01-22 17:49:21
【问题描述】:
我有几个 pandas 数据框,我想使用 numpy 作为三维 numpy 数组将它们堆叠起来。我可以使用以下代码手动完成这项工作:
arr = np.array([df1.values, df2.values], dtype="object")
但是,由于我有很多数据帧,我既不能为所有数据帧编写这一行,也不能自动化它。
我尝试使用 append 函数 (np.append(df1.values, df2['1002'].values)),但它会使数据帧变平并忽略它们的结构。我想要的是一个三维 numpy 数组,其中第一个维度是数据帧的数量(我拥有),第二个维度是每个数据帧中的行数,第三个维度是列数。在我之前提到的第一个示例中,我得到了一个 3D numpy 数组。事实上,当我运行arr.shape 时,结果是(2,),而当我运行arr[0].shape 和arr[1].shape 时,我分别得到(26, 7) 和(24, 7),它们分别是它们对应数据帧的结构。
我什至跑了np.append(df1.values, df2['1002'].values, axis=0),但我收到了ValueError: all the input array dimensions for the concatenation axis must match exactly的错误。有什么办法可以解决这个问题并将我的所有数据帧堆叠在一个 3 维 numpy 数组中?
【问题讨论】:
标签: python-3.x pandas dataframe numpy numpy-ndarray