Python将列表重塑为ndim数组
问题描述:
我有一个长度为2800的列表单元,其中包含28个变量中每个变量的100个结果:以下是2个变量4个结果的示例
Hi I have a list flat which is length 2800, it contains 100 results for each of 28 variables: Below is an example of 4 results for 2 variables
[0,
0,
1,
1,
2,
2,
3,
3]
我想将列表重塑为数组(2,4),以使每个变量的结果都在单个元素中.
I would like to reshape the list to an array (2,4) so that the results for each variable are in a single element.
[[0,1,2,3],
[0,1,2,3]]
答
您可以考虑重新整形,使新形状从扁平化的原始列表/数组中逐行填充(最后一个尺寸变化最快).
You can think of reshaping that the new shape is filled row by row (last dimension varies fastest) from the flattened original list/array.
一个简单的解决方案是将列表成形为(100,28)数组,然后将其转置:
An easy solution is to shape the list into a (100, 28) array and then transpose it:
x = np.reshape(list_data, (100, 28)).T
有关已更新示例的更新:
Update regarding the updated example:
np.reshape([0, 0, 1, 1, 2, 2, 3, 3], (4, 2)).T
# array([[0, 1, 2, 3],
# [0, 1, 2, 3]])
np.reshape([0, 0, 1, 1, 2, 2, 3, 3], (2, 4))
# array([[0, 0, 1, 1],
# [2, 2, 3, 3]])