如何将3D数组转换为数据框

时间:2018-09-06 01:54:03

标签: python-3.x pandas numpy multidimensional-array reshape

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

但是现在我想按这样的顺序将数组转换为看起来像

的数据框
df.columns=df.loc[0]+'_'+df.loc[1]
df=df.loc[[2]]
df
Out[429]: 
  Dat_mt an_1_mt an_2_s an_3_t an_4_inch an_5_km
2     23      45     67     78        89    9000

1 个答案:

答案 0 :(得分:0)

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)