2010-05-05 14 views
6

Supongamos que tengo dos matrices numpy de formafusión matriz indexada en Python

x = [[1,2] 
    [2,4] 
    [3,6] 
    [4,NaN] 
    [5,10]] 

y = [[0,-5] 
    [1,0] 
    [2,5] 
    [5,20] 
    [6,25]] 

hay una manera eficiente para fusionarlos de manera que tengo

xmy = [[0, NaN, -5 ] 
     [1, 2, 0 ] 
     [2, 4, 5 ] 
     [3, 6, NaN] 
     [4, NaN, NaN] 
     [5, 10, 20 ] 
     [6, NaN, 25 ] 

que puede implementar una función simple utilizando la búsqueda para encontrar el índice, pero esto no es elegante y potencialmente ineficaz para muchas matrices y grandes dimensiones. Cualquier puntero es apreciado.

Respuesta

8

Ver numpy.lib.recfunctions.join_by

Sólo funciona en matrices estructuradas o recarrays, por lo que hay un par de problemillas.

Primero debe estar al menos familiarizado con las matrices estructuradas. Consulte here si no lo está.

import numpy as np 
import numpy.lib.recfunctions 

# Define the starting arrays as structured arrays with two fields ('key' and 'field') 
dtype = [('key', np.int), ('field', np.float)] 
x = np.array([(1, 2), 
      (2, 4), 
      (3, 6), 
      (4, np.NaN), 
      (5, 10)], 
      dtype=dtype) 

y = np.array([(0, -5), 
      (1, 0), 
      (2, 5), 
      (5, 20), 
      (6, 25)], 
      dtype=dtype) 

# You want an outer join, rather than the default inner join 
# (all values are returned, not just ones with a common key) 
join = np.lib.recfunctions.join_by('key', x, y, jointype='outer') 

# Now we have a structured array with three fields: 'key', 'field1', and 'field2' 
# (since 'field' was in both arrays, it renamed x['field'] to 'field1', and 
# y['field'] to 'field2') 

# This returns a masked array, if you want it filled with 
# NaN's, do the following... 
join.fill_value = np.NaN 
join = join.filled() 

# Just displaying it... Keep in mind that as a structured array, 
# it has one dimension, where each row contains the 3 fields 
for row in join: 
    print row 

Este salidas:

(0, nan, -5.0) 
(1, 2.0, 0.0) 
(2, 4.0, 5.0) 
(3, 6.0, nan) 
(4, nan, nan) 
(5, 10.0, 20.0) 
(6, nan, 25.0) 

Hope que ayuda!

Edit1: Ejemplo agregado Edit2: Realmente no debería unirse con flotadores ... Se cambió el campo 'clave' a un int.

+1

Gracias por esta perspicaz respuesta. Para mi estupidez, ¿hay alguna forma sencilla de convertir la matriz de estructuras en ndarray? Gracias. – leon

+0

@leon - Aquí hay una forma (usando la matriz "join" en el ejemplo ...): join.view (np.float) .reshape ((join.size, 3)) Espero que ayude! –

+1

esto en realidad no funciona porque la primera columna se convierte como int. Es por eso que preguntaba. – leon

Cuestiones relacionadas