简体   繁体   English

将 numpy ndarray 数组元素展平为特征行

[英]Flatten a numpy ndarray array elements to rows of features

I have a 4D numpy array in which each column represents 1 quantity and the rows are a statistics derivatives of the quantities, like.我有一个 4D numpy array ,其中每列代表 1 个数量,行是数量的统计导数,例如。

[mean mean mean
 std  std  std
 med  med  med]

Let's say column 1 represents speed column 2 acceleration etc. I would like to flatten each column of the array for all the quantities available into a row of features forming:假设第 1 列代表speed 2 列acceleration等。我想将所有可用数量的数组的每一列展平成一行特征形成:

mean std med mean std med mean std med ...

To clarify my concern, I give the following MWE :为了澄清我的担忧,我给出了以下MWE

input_shape = (1,3,4)
n_sample =20

X = np.random.randint(1, 10, size=(n_sample, )+ input_shape)
X.shape
(20,1,3,4)

So the first 2 entiries of X are:所以 X 的前 2 个条目是:

X[:2]
array([[[[1, 7, 7, 8],
         [9, 3, 4, 1],
         [1, 1, 7, 1]]],


       [[[2, 8, 9, 4],
         [8, 4, 2, 7],
         [3, 9, 8, 4]]]])

The columns represent quantities q1, q2, q3, q4 and the rows represents the statistics: mean, std, med for each of the arrays.列代表数量q1, q2, q3, q4 ,行代表统计数据:每个数组的mean, std, med

Then I want to flatten these statistics for each quantity to row of features so that the end result is like this:然后我想将每个数量的这些统计数据展平为特征行,以便最终结果是这样的:

  q1_mean q1_std q1_med q2_mean q2_std q2_med q3_mean q3_std q3_med q4_mean q4_std q4_med
     1      9       1      7      3      1      7       4       7      8      1       1
     2      8       3      8      4      9      9       2       8      4      7       4  

So each array is a single observation.所以每个数组都是一个单一的观察。 So I can easily transform to a dataframe, adding appropriate column head(name).所以我可以轻松转换为数据框,添加适当的列标题(名称)。

If I understood correctly, this should do what you want:如果我理解正确,这应该做你想要的:

np.transpose(X,(0,1,3,2)).reshape(X.shape[0],-1)

Note that transposing axis 2 and 3 is necessary since reshape will be done in a row-major (C-style) order.请注意,转置轴 2 和 3 是必要的,因为重塑将以行​​主(C 样式)顺序完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM