2016-05-22 64 views
3

如果我有三個numpy的數組:串聯numpy的行元素

a = np.array([[1, 2], [3, 4],[5,6]]) 
b = np.array([[7, 8], [9,10],[11,12]]) 
c = np.array([[13, 14], [15,16], [17,18]]) 
dstacker = np.dstack((a,b,c)) 

我想這個保存到以下格式的文件:

1713, 2814, 3915, 41016, 51117, 61218 

已經嘗試了許多方法並具有搜索堆棧交換詳盡地說,我目前難住。我有什麼選擇?

回答

1

也許這不是最完美的解決方案,但我從一個慷慨的成員做的幫助下在這裏找到了我的格式問題 - 金剛:

new_dstack_list =[''.join([hex(ele) for ele in row]) for dim in dstacker for row in dim] #supplied by Donkey Kong 

number_of_elements = len(new_dstack_list) 

for i in range(0,number_of_elements): 
    new_dstack_list[i] = new_dstack_list[i].replace(' ', '').replace('0x', '') 

保存文件:

with open(save_file_path,'w') as f: 
    f.write(",".join(list)) 
    f.close() 

,現在輸出的是:再次

17d,28e,39f,4a10,5b11,6c12 

感謝您的幫助,它摹給我一個正確的方向!

1

這裏的適當10-powered比例縮放每個元素,總結模擬串聯作用後,量化的方法 -

# Calculate each elements number of digits 
pows = np.floor(np.log10(dstacker)).astype(int)+1 

# 10 powered scalings needed for each elements except the last column 
scale = (10**pows[:,:,1:])[:,:,::-1].cumprod(axis=-1)[:,:,::-1] 

# Finally get the concatenated number using the scalings and adding last col 
num = ((dstacker[:,:,:-1]*scale).sum(-1) + dstacker[:,:,-1]).ravel() 

剩餘的工作是寫1D輸出數組num到一個文件中。

採樣運行 -

In [7]: dstacker 
Out[7]: 
array([[[ 1, 27, 13], 
     [27800,  8, 14]], 

     [[54543, 559,  5], 
     [ 4, 10, 17776]], 

     [[ 5, 11, 17], 
     [ 6,  2, 18]]]) 

In [8]: pows = np.floor(np.log10(dstacker)).astype(int)+1 
    ...: scale = (10**pows[:,:,1:])[:,:,::-1].cumprod(axis=-1)[:,:,::-1] 
    ...: num = ((dstacker[:,:,:-1]*scale).sum(-1) + dstacker[:,:,-1]).ravel() 
    ...: 

In [9]: num 
Out[9]: array([ 12713, 27800814, 545435595, 41017776,  51117,  6218]) 
+0

這是一個很好的解決方案。當其中一個元素爲零時,有任何解決方法。 (那麼累計總和會給出不正確的值) – akilat90