Numpy.array(500x50),如何跨行连接,使其变为(500x1)

时间:2018-10-19 14:42:23

标签: python numpy

对于有经验的Python用户来说,这似乎是一个非常简单的问题

努力操作numpy.array,目前它是一个10位二进制数的500x50数组,我想将所有数字跨行连接在一起,以创建一个500x1数组

任何建议 谢谢

代码

Weight_Binary = np.array(Weight_int)
Weight_Binary=(np.array([np.binary_repr(a).zfill(10) 
     for b in Weight_Binary for a in b]).reshape(Weight_Binary.shape))

print(Weight_Binary.shape)
print(Weight_Binary)


(500, 50)
[['0110100010' '1011010010' '0000000000' ... '0100100101' '0100100000'
'0010000010']
['0000010011' '1010101000' '0011010100' ... '1000111110' '0000000010'
'1001101011']
['0101001000' '1000010000' '1101110111' ... '1011001001' '1000110000'
'0000001100']

我希望将这些数字跨行连接以提供500x1数组。或者在末尾创建一个新列,这是将这些数字连接在一起的结果,我可以在其中使用。

例如,一个单一的例子是

 Weight_Binary[0,0]+Weight_Binary[0,1]

 Output '01101000101011010010'

但是对于整个阵列

2 个答案:

答案 0 :(得分:0)

似乎您想使用np.concatenate将它们连接在任一轴上:

import numpy as np

shape_source = (4, 3)
shape_target = (4, 1)

np.random.seed(42)
array = np.random.randint(9, size=shape_source)

print(array)
# [[6 3 7]
#  [4 6 2]
#  [6 7 4]
#  [3 7 7]]

print(np.concatenate(array[:], axis=0))
# [6 3 7 4 6 2 6 7 4 3 7 7]

print(np.concatenate(np.matrix.transpose(array)[:], axis=0))
# [6 4 6 3 3 6 7 7 7 2 4 7]

答案 1 :(得分:0)

您可以在各列中使用join来连接二进制表示形式:

import numpy as np

np.random.seed(42)
weight_binary = np.random.randint(1000, size=(500, 50))
weight_binary = (np.array([np.binary_repr(a).zfill(10) for b in weight_binary for a in b]).reshape(weight_binary.shape))

result = np.array([''.join(column) for column in weight_binary])
print(result.shape)
print(result[0])

输出

(500,)
00011001100110110011110101110001000011100001101010000100011110101111000000010100100110011000011110010111010010001101011001010010100111001010000101011101011101000001100011110110011110100101110010000010101001010101001101001100000001010101011101111010110110011101110010010101100000010010111111111011101101000101000010100000011100101101001110010000010101001111110010111010111101011000100011000001110110100000111010011111111010101010010111011011101011101111110011111100001110001011110111101111011010101110