簡體   English   中英

如何將空數組與Numpy.concatenate連接?

[英]How to concatenate an empty array with Numpy.concatenate?

我需要創建一個特定大小的數組mxn填充空值,這樣當我concatenate到該數組時,初始值將被添加的值覆蓋。

我目前的代碼:

a = numpy.empty([2,2])  # Make empty 2x2 matrix
b = numpy.array([[1,2],[3,4]])    # Make example 2x2 matrix
myArray = numpy.concatenate((a,b))    # Combine empty and example arrays

不幸的是,我最終制作了一個4x2矩陣而不是2x2矩陣,其值為b。

反正是否有一個特定大小的實際空數組,所以當我連接到它時,它的值變成我的添加值而不是默認+添加值?

就像Oniow所說,連接正是你所看到的。

如果你想要'默認值'與常規標量元素不同,我建議你用NaNs初始化你的數組(作為你的'默認值')。 如果我理解你的問題,你想合並矩陣,以便常規標量將覆蓋你的'默認值'元素。

無論如何,我建議你添加以下內容:

def get_default(size_x,size_y):
    # returns a new matrix filled with 'default values'
    tmp = np.empty([size_x,size_y])
    tmp.fill(np.nan)
    return tmp

並且:

def merge(a, b):
    l = lambda x, y: y if np.isnan(x) else x
    l = np.vectorize(l)
    return map(l, a, b)

請注意,如果合並2個矩陣,並且兩個值都不是“默認”,那么它將采用左矩陣的值。

使用NaN作為默認值,將從默認值產生預期行為,例如,所有數學運算都將產生“默認”,因為此值表示您並不真正關心矩陣中的此索引。

如果我正確理解你的問題 - 連接不是你想要的。 如您所見,Concatenate執行: 沿軸連接。

如果您嘗試將空矩陣變為另一個的值,則可以執行以下操作:

import numpy as np

a = np.zeros([2,2])
b = np.array([[1,2],[3,4]])

my_array = a + b

- 要么 -

import numpy as np

my_array = np.zeros([2,2]) # you can use empty here instead in this case.

my_array[0,0] = float(input('Enter first value: ')) # However you get your data to put them into the arrays.

但是,我猜這不是你真正想要的,因為你可以使用my_array = b 如果您使用更多信息編輯您的問題,我可以提供更多幫助。

如果您擔心隨着時間的推移會向您的陣列添加值...

import numpy as np

a = np.zeros([2,2])

my_array = b # b is some other 2x2 matrix
''' Do stuff '''
new_b # New array has appeared
my_array = new_b # update your array to these new values. values will not add. 

# Note: if you make changes to my_array those changes will carry onto new_b. To avoid this at the cost of some memory:
my_array = np.copy(new_b)

暫無
暫無

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

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