简体   繁体   English

合并两个Numpy数组

[英]merging two Numpy Array

I have a very simple question ! 我有一个非常简单的问题! How can I merge two numpy array with increasing the dimension: 如何合并两个numpy数组并增加维度:

Suppose I have the following arrays : 假设我有以下数组:

a=[1,2]
b=[3,4,5]

I need this result : 我需要这个结果:

c=[[1,2],[3,4,5]

However 然而

np.concatenate((a,b),axis=0)

does not work ! 不起作用!

Thanks! 谢谢!

You can simply do the following to get the result you want. 您只需执行以下操作即可获得所需的结果。

c = [a,b]

Or 要么

c = np.array([a,b])

Result: 结果:

[[1, 2], [3, 4, 5]]

Put them together in a list: 将它们放到一个列表中:

In [269]: c = [a,b]
In [270]: c
Out[270]: [[1, 2], [3, 4, 5]]

Making an array from that doesn't work very well: 从中制作数组效果不佳:

In [271]: np.array(c)
Out[271]: array([list([1, 2]), list([3, 4, 5])], dtype=object)

But if your goal is just to write the lists to a file, csv style, we can do: 但是,如果您的目标只是将列表写入csv样式的文件中,我们可以这样做:

In [272]: for row in c:
     ...:     line=''
     ...:     for x in row:
     ...:         line += '%5s'%x
     ...:     print(line)
     ...:     
    1    2
    3    4    5

For a file just substitute the file write for the print . 对于文件,只需用写文件代替print

numpy has a nice savetxt but it requires a nice 2d array. numpy有一个不错的savetxt但它需要一个不错的2D数组。 That ragged 1d object dtype array does not work. 那个衣衫1的1d对象dtype数组不起作用。

itertools.zip_longest can also be used to 'pad' the elements of c . itertools.zip_longest也可以用于“填充” c的元素。 But simply writing to the file is simplest. 但是简单地写入文件是最简单的。

Using zip_longest to pad the rows, and then using savetxt to write the csv. 使用zip_longest填充行,然后使用savetxt编写csv。 Note the 'blank' delimited 'cell': 请注意以“空白”分隔的“单元格”:

In [321]: rows =list(zip(*zip_longest(*c,fillvalue='')))
In [322]: rows
Out[322]: [(1, 2, ''), (3, 4, 5)]
In [323]: np.savetxt('foo.txt',rows, fmt='%5s',delimiter=',')
In [324]: cat foo.txt
    1,    2,     
    3,    4,    5

with the proper padding, I can reload the csv (may need to fiddle with the fill value): 使用适当的填充,我可以重新加载csv(可能需要摆弄填充值):

In [328]: np.genfromtxt('foo.txt',delimiter=',')
Out[328]: 
array([[  1.,   2.,  nan],
       [  3.,   4.,   5.]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM