![](/img/trans.png)
[英]How to turn a 3d numpy array into a pandas dataframe of numpy 1d arrays?
[英]Merge 3D numpy array into pandas Dataframe + 1D vector
我有一个数据集,它是一个形状为 (1536 x 16 x 48) 的 numpy 数组。 这些维度的快速解释可能会有所帮助:
总之:我有 48 个 6 秒(1536 个值)的 EEG 数据样本,由 16 个电极收集。
我需要使用所有这些数据创建一个 pandas dataframe,因此将这个 3D 数组转换为 2D。 如果我将所有样本堆叠在一起,则可以删除深度尺寸(48)。 所以新数据集的形状将是 (1536 * 48) x 16。
除此之外,由于这是一个分类问题,我有一个包含 48 个值的向量,代表每个 EEG 样本的 class。 新数据集也应该将其作为“类”列,然后真正的形状将是:(1536 * 48) x 16 + 1(类)。
我可以轻松地循环遍历 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
Output
(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
。 - 列选择、添加、删除
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.