怎么将3D数组转换为数据帧

本教程将介绍如何将3D数组转换为数据帧的处理方法,这篇教程是从别的地方看到的,然后加了一些国外程序员的疑问与解答,希望能对你有所帮助,好了,下面开始学习吧。

怎么将3D数组转换为数据帧 教程 第1张

问题描述

我有一个维度数组(40 X 40 X 8064),它对应于(视频X频道X数据)。

但现在我想按如下顺序将数组转换为数据框:

Index  |  Video  |  Channel_0  |  Channel_1  |  Channel_2  |  ....  |  Channel_39
0|  0|[Some Value] |[Some Value] |[Some Value] |  ....  |[Some Value]
1|  0|[Some Value] |[Some Value] |[Some Value] |  ....  |[Some Value]
2|  0|[Some Value] |[Some Value] |[Some Value] |  ....  |[Some Value]
3|  0|[Some Value] |[Some Value] |[Some Value] |  ....  |[Some Value]
4|  0|[Some Value] |[Some Value] |[Some Value] |  ....  |[Some Value]
...............
8063|  0|[Some Value] |[Some Value] |[Some Value] |  ....  |[Some Value]
......
......
322559 |  39|[Some Value] |[Some Value] |[Some Value] |  ....  |[Some Value]

推荐答案

import numpy as np
import pandas as pd

n_videos = 2
n_channels = 3
n_points = 4

# Generate data
A = np.arange(n_videos * n_channels * n_points).reshape(n_videos,
  n_channels,
  n_points)

col_names = ["Channel_{}".format(i) for i in range(n_channels)]
# Need to re-order axis before reshape. 
# Want axis correspoonding to videos to be at first axis.
df = pd.DataFrame(np.rollaxis(A, 2, 1).reshape(-1, n_channels),
columns=col_names)
video_idx = np.hstack((np.full((n_points,), i) for i in range(n_videos)))
video_idx = pd.Series(video_idx, name="Video")
df.insert(0, "Video", video_idx)

好了关于怎么将3D数组转换为数据帧的教程就到这里就结束了,希望趣模板源码网找到的这篇技术文章能帮助到大家,更多技术教程可以在站内搜索。