簡體   English   中英

是否可以一次初始化多個數組?

[英]Is it possible to initialise more than one array at a time?

我有這個數組:

A = array([[450.,   0., 509., 395.,   0.,   0., 449.],
          [490.,   0., 572., 357.,   0.,   0., 489.],
          [568.,   0., 506., 227.,   0.,   0., 567.]])
A.shape = (3, 7)

我想創建 3 個不同的空 arrays,名稱逐漸增加,原始行的每一行為 append。

example: 
array1 = [450.,   0., 509., 395.,   0.,   0., 449.]
array2 = [490.,   0., 572., 357.,   0.,   0., 489.]
array3 = [568.,   0., 506., 227.,   0.,   0., 567.]

這只是一個例子,考慮到我應該使用一個比這行多得多的初始數組。 因此,假設我需要創建與原始行數一樣多的 arrays 和每行 append 的順序。 希望我很清楚。

更新:

我有一個包含 500 行的 swc 文件,與數組 A 中的行相似。使用 for 循環,我必須找到第一列中的行與數組 A 的第 6 列之一具有相同值的行。如果滿足該列應附加到適當數組的條件。

例子:

在我的 swc 文件中,我有這 3 行滿足我的條件:

[449.   0. 510. 394.   0.   0. 448.]
[489.   0. 571. 357.   0.   0. 488.]
[567.   0. 505. 228.   0.   0. 566.]

所以我需要將它們 append 到適當的數組。 假設我手動創建了 arrays:

array1 = [450.,   0., 509., 395.,   0.,   0., 449.]
array2 = [490.,   0., 572., 357.,   0.,   0., 489.]
array3 = [568.,   0., 506., 227.,   0.,   0., 567.], 

我希望這樣:

array1 = [450.,   0., 509., 395.,   0.,   0., 449.], [449.   0. 510. 394.   0.   0. 448.]
    array2 = [490.,   0., 572., 357.,   0.,   0., 489.], [489.   0. 571. 357.   0.   0. 488.]
    array3 = [568.,   0., 506., 227.,   0.,   0., 567.], [567.   0. 505. 228.   0.   0. 566.]

簡短的回答

以下 2-liner 將為您提供所需的結果

cond = A[:,0]-1 == A[:,6] # compare columns 1 and 7, find ones that match (well, with -1...check details)
np.concatenate((A[cond,:],A[cond,:]),axis=0) # append rows that meet the condition to respective rows

細節和解釋

這可以通過以下方式相當有效地完成(請注意,您說第 1 列和第 6 列必須匹配,但在問題中,您顯示的結果是第 7 列中的值是第 1 列中的 -1 和第 2 列等於第 6 列。不清楚你想要什么,所以我假設它是前者(沒關系,真的,它可以很容易地更新))。

查找滿足條件的行

# find which rows satisfy your condition in your swc array
# compare columns 1 and 7 (note, Python indexes from 0, not 1)
cond = A[:,0]-1==A[:,6] # can also do A[:,1]==A[:,5] ..you get the point

# return the rows that meet the condition of equal column values within rows
A[cond,:] # this is just for illustrative purposes, not really needed for the task

Append 滿足條件的行到滿足條件的行

對於最后一部分的附加部分,從你的問題中並不清楚你想要 append。

按行附加:由於您想要的結果實際上不是有效的分配

array1 = [450.,   0., 509., 395.,   0.,   0., 449.], [449.   0. 510. 394.   0.   0. 448.]

我只能假設你的意思是

array1 = np.array([[450.,   0., 509., 395.,   0.,   0., 449.], [449. ,  0., 510. ,394.  , 0.  , 0. ,448.]])

這意味着array1是一個 2x7 數組,因此所需的附加是row-wise (按列會給你一個 1x14 數組)

假設我的推論是正確的,那么您只需將矩陣連接起來即可:

# append (row-wise, as your operation of appending to `array1` would suggest) to relevant subset
B = np.concatenate((A[cond,:],A[cond,:]),axis=0)
B.shape

因此, B矩陣的形狀為 6x7(3x7 原始加上 3x7 副本),如您所願。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM