【问题标题】:Construct Pandas Panel from 2D structured NumPy array从二维结构化 NumPy 数组构建 Pandas 面板
【发布时间】:2017-03-08 15:04:41
【问题描述】:

我有一个二维 NumPy 结构数组:

arr = np.zeros((3,5), [('x',int), ('y',float)])

即:

array([[(0, 0.0), (0, 0.0), (0, 0.0), (0, 0.0), (0, 0.0)],
       [(0, 0.0), (0, 0.0), (0, 0.0), (0, 0.0), (0, 0.0)],
       [(0, 0.0), (0, 0.0), (0, 0.0), (0, 0.0), (0, 0.0)]], 
      dtype=[('x', '<i8'), ('y', '<f8')])

我想用它创建一个 Pandas 面板。我尝试了明显的:

pd.Panel(arr)

ValueError: The number of dimension required is 3, but the number of ndarray given was 2

然后我发现了这个可怕的一堆:

pd.Panel(dict(enumerate(pd.DataFrame(a) for a in arr)))

它产生:

<class 'pandas.core.panel.Panel'>
Dimensions: 3 (items) x 5 (major_axis) x 2 (minor_axis)
Items axis: 0 to 2
Major_axis axis: 0 to 4
Minor_axis axis: x to y

这“有效”,但效率非常低且令人眼花。

如何构建此类面板?

编辑:我在这里提交了一个问题:https://github.com/pandas-dev/pandas/issues/14511

【问题讨论】:

  • 你想要的最终形状是什么?类似pd.Panel(arr.reshape((1, arr.shape[0], arr.shape[1])))pd.Panel(arr.reshape(( arr.shape[0], arr.shape[1],1)))?
  • @EdChum:我在问题中写的丑陋的一堆给出的最终形状是可以的。您编写的代码确实生成了面板,但它们充满了 NaN,而不是来自 arr 的数据!!我将更新问题以显示可怕堆的结果。

标签: pandas numpy panel-data


【解决方案1】:

您需要提供一个与面板对象的项目、长轴和短轴相对应的 3-D 数组。

# minor axis corresponds to the dtype names of the array initialized with zeros
dtyp = np.array(arr.dtype.names)
# dimensions to be included 
dim = arr.shape[0], arr.shape[1], dtyp.shape[0]
# Flatten the array and reshape it according to the aforementioned dimensions
panel = pd.Panel(pd.DataFrame(arr.ravel()).values.reshape(dim), minor_axis=dtyp)

给予:

<class 'pandas.core.panel.Panel'>
Dimensions: 3 (items) x 5 (major_axis) x 2 (minor_axis)
Items axis: 0 to 2
Major_axis axis: 0 to 4
Minor_axis axis: x to y

要将其转换为DF,只需使用to_frame 方法,如下所示:

panel.to_frame()

时间安排:

【讨论】:

  • 你的方法确实更快,但比我原来的更不简洁。您提到 Panel 需要 3D 数组,但显然这正是 2D 结构化数组。毕竟,可以从一维结构化数组构造 DataFrame。我猜这只是 Panel 构造函数的一个缺点。
  • 是的,我同意这一点。与数据框/系列对应物相比,当前面板对象的功能较低。将来一定有办法处理3轴numpy数组构造。
  • 我刚刚意识到您的解决方案的另一个问题:它将所有项目类型更改为浮动!我需要保留原始数据类型,因为在实践中我还使用布尔值、字符串、日期时间等。
  • 从你的起始数组构造的面板对象在同一列中包含 intfloat 值(由于短轴创建的多索引),这种行为是合理的.在这种情况下,dtypes 会因为类型的混合而被推断为浮点数。因此,您将所有项目轴的dtypes 设为float64。此外,在使用您的原始函数时会观察到相同的行为。
  • 事实证明这种行为根本不合理...如果您查看我在 GitHub 上发布的问题的回复(并在问题中添加了链接),您会看到维护人员Pandas 的人说 Panel 已被弃用并且没有得到维护,人们应该切换到 xarray(与 Pandas 完全不同的库)。奇怪。
猜你喜欢
  • 1970-01-01
  • 2011-06-22
  • 2015-07-13
  • 2021-12-06
  • 2023-03-16
  • 1970-01-01
  • 2019-09-02
  • 1970-01-01
  • 2013-03-06
相关资源
最近更新 更多