2013-05-21 8 views
6

Perché l'inserimento di un nuovo asse rende i dati non contigui?L'asse di inserimento numpy rende i dati non contigui

>>> a = np.arange(12).reshape(3,4,order='F') 
>>> a 
array([[ 0, 3, 6, 9], 
     [ 1, 4, 7, 10], 
     [ 2, 5, 8, 11]]) 
>>> a.reshape((3,1,4)).flags 
    C_CONTIGUOUS : False 
    F_CONTIGUOUS : False 
    OWNDATA : False 
    WRITEABLE : True 
    ALIGNED : True 
    UPDATEIFCOPY : False 
>>> a[np.newaxis,...].flags 
    C_CONTIGUOUS : False 
    F_CONTIGUOUS : False 
    OWNDATA : False 
    WRITEABLE : True 
    ALIGNED : True 
    UPDATEIFCOPY : False 
>>> a.flags 
    C_CONTIGUOUS : False 
    F_CONTIGUOUS : True 
    OWNDATA : False 
    WRITEABLE : True 
    ALIGNED : True 
    UPDATEIFCOPY : False 

Nota che se uso C ordinazione, lo fa mantenere i dati contigui quando ho rimodellare, ma non quando aggiungo un nuovo asse:

>>> a 
array([[ 0, 1, 2, 3], 
     [ 4, 5, 6, 7], 
     [ 8, 9, 10, 11]]) 
>>> a.flags 
    C_CONTIGUOUS : True 
    F_CONTIGUOUS : False 
    OWNDATA : False 
    WRITEABLE : True 
    ALIGNED : True 
    UPDATEIFCOPY : False 

>>> a.reshape(3,1,4).flags 
    C_CONTIGUOUS : True 
    F_CONTIGUOUS : False 
    OWNDATA : False 
    WRITEABLE : True 
    ALIGNED : True 
    UPDATEIFCOPY : False 
>>> a[np.newaxis,...].flags 
    C_CONTIGUOUS : False 
    F_CONTIGUOUS : False 
    OWNDATA : False 
    WRITEABLE : True 
    ALIGNED : True 
    UPDATEIFCOPY : False 

aggiornamento Per coloro che potrebbero trovare questo in una ricerca, per mantenere l'ordine dell'array corrente in una risagoma, a.reshape(3,1,4,order='A') funziona e mantiene contiguo un array contiguo.


Per coloro che chiedono "Perché ti interessa?", Questo fa parte di un copione che passa le matrici per FORTRAN per alcune subroutine FORTRAN compilate tramite f2py. Le routine di Fortran richiedono dati 3D, quindi riempirò gli array di nuove dimensioni per portarli al numero richiesto di dimensioni. Mi piacerebbe mantenere dati contigui per evitare comportamenti di copia-in/copia.

+3

Bene è strano ... –

+1

@JoeKington - Sì. Lo pensavo anch'io. Da quando ho scoperto 'order = 'A'', posso semplicemente usare' ndarray.reshape'. Preferirei 'np.newaxis' anche se' data = a [newaxis, ...] 'sembra più pulito di' data = a.reshape ((1,) + a.shape, order = 'A') ' – mgilson

+0

Scommetto che questo si riferisce alla gigantesca discussione sulla mailing list numpy recentemente: http://numpy-discussion.10968.n7.nabble.com/Ravelling-reshape-order-keyword-unnecessarily-confuses-index-and-memory -ordering-td33355.html Concordo sul fatto che sia confuso! Non avrei mai immaginato che tagliare con 'newaxis' lo avrebbe fatto! –

risposta

1

questo non risponde alla tua domanda, ma può essere di qualche utilità: È anche possibile fare uso di numpy.require np.require(a[np.newaxis,...], requirements='FA').flags
C_CONTIGUOUS : False
F_CONTIGUOUS : True
OWNDATA : True
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False

Problemi correlati