Python将列表重塑为ndim数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35432378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:26:20  来源:igfitidea点击:

Python reshape list to ndim array

pythonnumpyreshape

提问by BenP

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

嗨,我有一个长度为 2800 的列表平面,它包含 28 个变量中的每一个的 100 个结果:下面是 2 个变量的 4 个结果的示例

[0,
 0,
 1,
 1,
 2,
 2,
 3,
 3]

I would like to reshape the list to an array (2,4) so that the results for each variable are in a single element.

我想将列表重塑为数组 (2,4),以便每个变量的结果都在一个元素中。

[[0,1,2,3],
 [0,1,2,3]]

采纳答案by kazemakase

You can think of reshaping that the new shape is filled row by row (last dimension varies fastest) from the flattened original list/array.

您可以考虑将新形状从展平的原始列表/数组中逐行填充(最后一个维度变化最快)。

An easy solution is to shape the list into a (100, 28) array and then transpose it:

一个简单的解决方案是将列表整形为 (100, 28) 数组,然后将其转置:

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]])

回答by cristiandatum

Step by step:

一步步:

# import numpy library
import numpy as np
# create list
my_list = [0,0,1,1,2,2,3,3]
# convert list to numpy array
np_array=np.asarray(my_list)
# reshape array into 4 rows x 2 columns, and transpose the result
reshaped_array = np_array.reshape(4, 2).T 

#check the result
reshaped_array
array([[0, 1, 2, 3],
       [0, 1, 2, 3]])

回答by Vinay Verma

The answers above are good. Adding a case that I used. Just if you don't want to use numpy and keep it as list without changing the contents.

楼上的回答都不错。添加我使用的案例。只是如果您不想使用 numpy 并将其保留为列表而不更改内容。

You can run a small loop and change the dimension from 1xN to Nx1.

您可以运行一个小循环并将维度从 1xN 更改为 Nx1。

    tmp=[]
    for b in bus:
        tmp.append([b])
    bus=tmp

It is maybe not efficient while in case of very large numbers. But it works for a small set of numbers. Thanks

在非常大的数字的情况下,它可能效率不高。但它适用于一小组数字。谢谢