簡體   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