Search code examples
pythonarraysnumpyrecordrecarray

Concatenating numpy record arrays with same fields in different order


I have two ndarrays with "compatible" but non-identical dtypes, like this:

In [22]: A = numpy.empty(shape=(5), dtype=[("A", "f4"), ("B", "f4")])

In [23]: B = numpy.empty(shape=(5), dtype=[("B", "f4"), ("A", "f4")])

In [24]: numpy.concatenate((A, B))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-24-c930307fb7e4> in <module>()
----> 1 numpy.concatenate((A, B))

TypeError: invalid type promotion

Short of concatenating explicitly field by field, is there a way to concatenate the two?


How did I get to this situation? I'm not sure, possibly a bug earlier in my code, but regardless of me fixing the earlier bug, I'm curious of the answer.


Solution

  • Not a numpy expert but this may work as you want.

    import numpy.lib.recfunctions
    
    
    In [35]: numpy.lib.recfunctions.stack_arrays([A,B], usemask = False)
    Out[35]: 
    array([(0.0, 0.0), (-3.935500814122861e-10, 4.579443381413502e-41),
           (-4.456803814889554e-10, 4.579443381413502e-41),
           (-8.571845455662697e-09, 4.579443381413502e-41),
           (6.726232628759122e-44, 0.0), (0.0, 0.0),
           (4.579443381413502e-41, -3.935500814122861e-10),
           (4.579443381413502e-41, -4.456803814889554e-10),
           (4.579443381413502e-41, -8.571845455662697e-09),
           (0.0, 6.726232628759122e-44)], 
          dtype=[('A', '<f4'), ('B', '<f4')])