0

I have an array with a few record fields.

arr=np.array([[(0,1,3)]],dtype=[('A','i4'),('B','i4'),('C','u4')])
print(arr)
[[(0, 1, 3)]]

I'd like to add a new column and to get an array like this one:

arr2=np.array([[(0,1,3,0)]],dtype=[('A','i4'),('B','i4'),('C','u4'),('D','i4')])
print(arr2)
[[(0, 1, 3, 0)]]

...or to get an array like this one:

arr3=np.array([[(0,1,3)],[(11,22,33)]],dtype=[('A','i4'),('B','i4'),('C','u4')])
print(arr3)
[[( 0,  1,  3)]
 [(11, 22, 33)]]

Could anybody help me with it?

  • 1
    Have you seen https://stackoverflow.com/questions/1201817/adding-a-field-to-a-structured-numpy-array, https://stackoverflow.com/questions/5288736/adding-a-field-to-a-structured-numpy-array-2, https://stackoverflow.com/questions/53137822/adding-a-field-to-a-structured-numpy-array-4? – Warren Weckesser Dec 03 '19 at 19:27
  • No, I have not. Thank you for reccomendations. – Paul Chupakhin Dec 03 '19 at 19:38
  • 1
    As long as the `dtypes` match you can use the usual `concatenate`. To add new field look at `np.lib.recfunctions` functions. – hpaulj Dec 03 '19 at 20:04

1 Answers1

1
import numpy as np

n = 4
m = 5
arr=np.array([[(3*(j*n + i),3*(j*n + i)+1,3*(j*n + i)+2) for i in range(n)] for j in range(m)],dtype=[('A','i4'),('B','i4'),('C','u4')])

c = np.array([[(i*j,) for i in range(1,n+1)] for j in range(1,m+1)],dtype=[('D','i4')])

arr2 = np.zeros(arr.shape,dtype=[('A','i4'),('B','i4'),('C','u4'),('D','i4')])

arr2[['A','B','C']] = arr[['A','B','C']]
arr2['D'] = c

iliar
  • 932
  • 6
  • 11