import numpy as np
def main():
my_tuples = np.array(((1,-2,3),(4,5,6)))
element = (7,8) #suppose you want to add this to my_tuples column
#Solution 1
print('shape before adding column', my_tuples.shape)
new_tuples = np.zeros((my_tuples.shape[0],my_tuples.shape[1]+1));
new_tuples[:,:-1] = my_tuples
new_tuples[:,-1] = element
print('column to be added ', element)
print('shape after adding column using np.zeros', new_tuples.shape)
print(new_tuples)
#Solution 2
new_tuples = np.hstack((my_tuples,np.zeros((my_tuples.shape[0],1))))
new_tuples[:,-1] = element
print('shape after adding column using np.hstack', new_tuples.shape)
print(new_tuples)
if __name__ == '__main__':
main()
输出:
shape before adding column (2, 3)
column to be added (7, 8)
shape after adding column using np.zeros (2, 4)
[[ 1. -2. 3. 7.]
[ 4. 5. 6. 8.]]
shape after adding column using np.hstack (2, 4)
[[ 1. -2. 3. 7.]
[ 4. 5. 6. 8.]]
我想我找到了一个解决方案,它涉及到向结构数组中添加列:
由于这个问题没有答案,我写了一个可能有用的片段。可以使用
np.zeros
或np.hstack
向数组中添加新列。你知道吗输出:
相关问题 更多 >
编程相关推荐