我有一个numpy数组,其形状(n,)是一个包含多个元素的元组数组。有没有办法让我快速添加一个列到其中一个元组和&它仍然具有相同的形状(n,)?
答案 0 :(得分:0)
由于这个问题没有答案,我写了一个可能有帮助的片段。您可以使用np.zeros
或np.hstack
向阵列添加新列。
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.]]
答案 1 :(得分:0)
我认为我找到了一个解决方案,它为结构数组添加了一个列:
from numpy.lib import recfunctions
a = recfunctions.append_fields(old_data,'new_column',
new_array,dtypes=np.float64,
usemask=False)