gpt4 book ai didi

pandas - 从二维结构化 NumPy 数组构造 Pandas 面板

转载 作者:行者123 更新时间:2023-12-01 13:41:03 24 4
gpt4 key购买 nike

我有一个 2D 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 dimensions required is 3, but the number of dimensions of the 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

最佳答案

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

# 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()

Image

时间:

Image

关于pandas - 从二维结构化 NumPy 数组构造 Pandas 面板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40259034/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com