繁体   English   中英

Python和从列表创建2d numpy数组

[英]Python and creating 2d numpy arrays from list

我在将列中的值转换为Numpy 2d数组时遇到了一些麻烦。 我的代码输出如下:

38617.0 0 0
40728.0 0 1
40538.0 0 2
40500.5 0 3
40214.0 0 4
40545.0 0 5
40352.5 0 6
40222.5 0 7
40008.0 0 8
40017.0 0 9
40126.0 0 10
40029.0 0 11
39681.5 0 12
39973.0 0 13
39903.0 0 14
39766.5 0 15
39784.0 0 16
39528.5 0 17
39513.5 0 18

并持续约30万行。 数据的坐标排列为(z,x,y),我想将其转换为尺寸为765X510(x,y)的2d数组,以便z坐标位于各自的(x,y)坐标,以便我可以将其写入图像文件。

有任何想法吗? 我一直在环顾四周,但至今未发现任何问题。


编辑:

这是创建以上数据列的while循环(实际上是两个,在另一个while循环中调用了一个函数):

def make_median_image(x,y):
        while y < 509:
                y = y + 1 # Makes the first value (x,0), b/c Python is indexed at 0
                median_first_row0 = sc.median([a11[y,x],a22[y,x],a33[y,x],a44[y,x],a55[y,x],a66[y,x],a77[y,x],a88[y,x],a99[y,x],a1010[y,x]])
                print median_first_row0,x,y
                list1 = [median_first_row0,x,y]
                list = list1.append(

while x < 764:
        x = x + 1
        make_median_image(x,y)
import numpy as np
l = [[1,2,3], [4,5,6], [7,8,9], [0,0,0]]

您可以将python 2D列表直接传递到numpy数组中。

>>> np.array(l)
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9],
       [0, 0, 0]])

如果只需要后两列(即您的x,y值)

>>> np.array([[i[1],i[2]] for i in l])
array([[2, 3],
       [5, 6],
       [8, 9],
       [0, 0]])

这样可以从下面的数据创建一个数组吗?

数据:

38617.0 0 0
40728.0 0 1
40538.0 0 2
40500.5 0 3
40214.0 0 4
40545.0 0 5
40352.5 0 6
40222.5 0 7
40008.0 0 8
40017.0 0 9
40126.0 0 10
40029.0 0 11
39681.5 0 12
39973.0 0 13
39903.0 0 14
39766.5 0 15
39784.0 0 16
39528.5 0 17
39513.5 0 18
... (continues for ~100,000 lines, so you can guess why I'm adamant to find an answer)

我想要的是:

numpy_ndarray = [[38617.0, 40728.0, 40538.0, 40500.5, 40214.0, 40545.0, 40352.5, ... (continues until the last column value in the data above is 764) ], [begin next line, when x = 1, ... (until last y-value is 764)], ... [ ... (some last pixel value)]]

因此,它基本上从与第二列和第三列中的(x,y)坐标相关联的数据的第一列中的像素值构建一个矩阵/图像网格。

假设您的数组是l

import numpy as np
l = [[1,2,3], [4,5,6], [7,8,9], [0,0,0]]

>>> np.array(l)
array([[1, 2, 3],
   [4, 5, 6],
   [7, 8, 9],
   [0, 0, 0]])

这应该工作

>>> np.array([[i[1] for i in l],[i[2] for i in l]])
array([[2, 5, 8, 0],
   [3, 6, 9, 0]])

暂无
暂无

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

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