将 3D numpy 数组合并到 pandas Dataframe + 1D 向量中

Merge 3D numpy array into pandas Dataframe + 1D vector

我有一个数据集,它是一个形状为 (1536 x 16 x 48) 的 numpy 数组。对这些维度的快速解释可能会有帮助:

总而言之:我有 48 个 6 秒(1536 个值)的 EEG 数据样本,由 16 个电极收集。

我需要用所有这些数据创建一个 pandas 数据框,然后将这个 3D 数组转换为 2D。如果我将所有样本一个接一个地堆叠,则可以删除深度维度 (48)。所以新数据集的形状将是 (1536 * 48) x 16.

除此之外,由于这是一个 class 化问题,我有一个包含 48 个值的向量,代表每个 EEG 样本的 class。新数据集也应该将其作为“class”列,然后实际形状将是:(1536 * 48) x 16 + 1 (class).

我可以很容易地循环遍历 3D 数组的深度维度并将所有内容连接成一个 2D 新数组。但这看起来很糟糕,因为我将处理许多像这样的数据集。性能是一个问题。我想知道有没有更聪明的方法。

我已尽力为这个问题提供尽可能多的信息,但由于这不是一项微不足道的任务,如有需要,请随时询问更多详细信息。

提前致谢。

对于 numpy 部分

x = np.random.random((1536, 16, 48)) # ndarray with simillar shape
x = x.swapaxes(1,2) # swap axes 1 and 2 i.e 16 and 48
x = x.reshape((-1, 16), order='C') # order is important, you may want to check the docs
c = np.zeros((x.shape[0], 1)) # class column, shape=(73728, 1)
x = np.hstack((x, c)) # final dataset
x.shape

输出

(73728, 17)

或一行

x = np.hstack((x.swapaxes(1,2).reshape((-1, 16), order='C'), c))

最后,

x = pd.DataFrame(x)

设置

>>> import numpy as np
>>> import pandas as pd
>>> a = np.zeros((4,3,3),dtype=int) + [0,1,2]
>>> a *= 10
>>> a += np.array([1,2,3,4])[:,None,None]
>>> a
array([[[ 1, 11, 21],
        [ 1, 11, 21],
        [ 1, 11, 21]],

       [[ 2, 12, 22],
        [ 2, 12, 22],
        [ 2, 12, 22]],

       [[ 3, 13, 23],
        [ 3, 13, 23],
        [ 3, 13, 23]],

       [[ 4, 14, 24],
        [ 4, 14, 24],
        [ 4, 14, 24]]])

沿最后一个维度均匀分割;堆叠这些 元素 ,重塑形状,馈送至 DataFrame。使用数组维度的长度可以简化过程。

>>> d0,d1,d2 = a.shape
>>> pd.DataFrame(np.stack(np.dsplit(a,d2)).reshape(d0*d2,d1))
     0   1   2
0    1   1   1
1    2   2   2
2    3   3   3
3    4   4   4
4   11  11  11
5   12  12  12
6   13  13  13
7   14  14  14
8   21  21  21
9   22  22  22
10  23  23  23
11  24  24  24
>>>

使用你的形状。

>>> b = np.random.random((1536, 16, 48))
>>> d0,d1,d2 = b.shape
>>> df = pd.DataFrame(np.stack(np.dsplit(b,d2)).reshape(d0*d2,d1))
>>> df.shape
(73728, 16)
>>>

从 3d 数组制作 DataFrame 后,向其添加分类列,df['class'] = data。 - Column selection, addition, deletion