连接numpy行元素

时间:2016-05-22 07:31:06

标签: python-3.x

如果我有三个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

尝试了很多方法并且详尽地搜索了堆栈交换,我目前难倒了。我有什么选择?

2 个答案:

答案 0 :(得分:1)

也许这不是最优雅的解决方案,但我通过在这里慷慨的成员的帮助下做了以下几点来解决我的格式问题 - Donkey Kong:

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 :(得分: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])