如何将所有信息从 3d numpy 数组导出到 csv 文件

How to export all the information from 3d numpy array to a csv file

Kaggle Dataset and code link

我正在尝试解决上述 Kaggle 问题,我想导出预处理的 csv,以便我可以在 weka 上构建模型,但是当我尝试将其保存在 csv 中时,我丢失了一个维度,我想保留该 csv 中的所有信息。

请帮助我提供相关代码或任何资源。

谢谢

print (scaled_x)

    |x           |y          |z          |label
    |1.485231    |-0.661030  |-1.194153  |0
    |0.888257    |-1.370361  |-0.829636  |0
    |0.691523    |-0.594794  |-0.936247  |0
Fs=20
frame_size = Fs*4 #80
hop_size = Fs*2 #40
    
def get_frames(df, frame_size, hop_size):
    N_FEATURES = 3
    frames = []
    labels = []
    for i in range(0,len(df )- frame_size, hop_size):
        x = df['x'].values[i: i+frame_size]
        y = df['y'].values[i: i+frame_size]
        z = df['z'].values[i: i+frame_size]
        
        label = stats.mode(df['label'][i: i+frame_size])[0][0]
        frames.append([x,y,z])
        labels.append(label)
        
    frames = np.asarray(frames).reshape(-1, frame_size, N_FEATURES)
    labels = np.asarray(labels)
    
    return frames, labels
x,y = get_frames(scaled_x, frame_size, hop_size)
    x.shape, y.shape

((78728, 80, 3), (78728,))

根据您发布的 link,数据是时间序列 accelerometer/gyro 数据,采样频率为 20 Hz,每个样本都有一个标签。他们想将时间序列聚合成帧(相应的标签是给定帧中最常见的标签)。

所以frame_size是一帧中的样本数,hop_size是滑动window每次迭代向前移动的量。换句话说,自 hop_size = frame_size / 2.

以来,帧重叠了 50%

因此最后你得到一个 78728 帧长度为 80 的 3D 数组,每个有 3 个值(xyz)。

编辑:要回答关于如何导出为 CSV 的新问题,您需要将 3D 帧数组“展平”为 2D 数组,因为这就是 CSV代表。有多种不同的方法可以做到这一点,但我认为最简单的可能只是连接最后的两个维度,这样每一行都是一个框架,由 240 个值组成(每个 3 个坐标的 80 个样本)。然后连接标签作为最后一列。

x_2d = np.reshape(x, (x.shape[0], -1))
full = np.concatenate([x, y], axis=1)

import pandas as pd
df = pd.DataFrame(full)
df.to_csv("frames.csv")

如果您还想要正确的列名:

columns = []
for i in range(1, x.shape[1] + 1):
    columns.extend([f"{i}_X", f"{i}_Y", f"{i}_Z"])
columns.append("label")
df = pd.DataFrame(full, columns=columns)