【问题标题】:Merge 3D numpy array into pandas Dataframe + 1D vector将 3D numpy 数组合并到 pandas Dataframe + 1D 向量中
【发布时间】:2021-04-24 03:52:55
【问题描述】:

我有一个数据集,它是一个形状为 (1536 x 16 x 48) 的 numpy 数组。对这些维度的简要说明可能会有所帮助:

  • 数据集由 EEG 传感器以 256Hz 的速率(1 秒 = 256 个测量值/值)收集的数据组成;
  • 1536 个值代表 6 秒的 EEG 数据 (256 * 6 = 1536);
  • 16 是用于收集数据的电极数量;
  • 48 是样本数。

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

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

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

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

我试图为这个问题提供尽可能多的信息,但由于这不是一项简单的任务,如果需要,请随时询问更多细节。

提前致谢。

【问题讨论】:

标签: python arrays pandas numpy classification


【解决方案1】:

设置

>>> 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

【讨论】:

    【解决方案2】:

    对于 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)
    

    【讨论】:

    • 我正在尝试重现您的代码,但出现以下错误:TypeError: 'tuple' object is not callable。你知道它是什么吗?
    • 打错字了,c = np.zeros((x.shape(0), 1)) 应该是c = np.zeros((x.shape[0], 1))。现已修复。
    • 这是将 3D 数组转换为 2D 的一种非常好的方法,但是将 48 长度的向量连接到新数组中的部分呢?在您的示例中,您将c 向量连接为具有73728 值的向量,而不是48
    • 根据您的帖子,数组形状应为 (1536 * 48) x 16 + 1 = 73728x17。因此,73728 个样本、16 个特征列和一个分类列。当你说连接 48 长度的向量时,你指的是哪个维度?
    猜你喜欢
    • 1970-01-01
    • 2013-01-08
    • 2020-04-22
    • 2013-02-12
    • 2022-08-03
    • 2016-11-21
    • 1970-01-01
    • 1970-01-01
    • 2020-06-23
    相关资源
    最近更新 更多