![](/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.