[Baypiggies] Question about collecting lower/upper triangle elements from a python array

Paul Ivanov pivanov314 at gmail.com
Wed Apr 13 02:47:16 CEST 2011


Another way, which is slower, but more flexible, depending on
what you need to do (e.g. to be able to edit the triangular
elements in place, or use a diagonal offset): np.tril_indices 

You can also use the np.tril_indices_from - which takes an array
as it's first argument.


Joe's example would be just:

In [1]: A = np.array([[2,4,6],[8,10,12], [14,16,18]])

In [2]: A[np.tril_indices_from(A)]
Out[2]: array([ 2,  8, 10, 14, 16, 18])


from the docstring:

>>> il1 = np.tril_indices(4)

Here is how they can be used with a sample array:

>>> a = np.arange(16).reshape(4, 4)
>>> a
array([[ 0,  1,  2,  3],
   [ 4,  5,  6,  7],
   [ 8,  9, 10, 11],
   [12, 13, 14, 15]])

Both for indexing:

>>> a[il1]
array([ 0,  4,  5,  8,  9, 10, 12, 13, 14, 15])

And for assigning values:

>>> a[il1] = -1
>>> a
array([[-1,  1,  2,  3],
   [-1, -1,  6,  7],
   [-1, -1, -1, 11],
   [-1, -1, -1, -1]])


best,
-- 
Paul Ivanov
314 address only used for lists,  off-list direct email at:
http://pirsquared.org | GPG/PGP key id: 0x0F3E28F7 


Yiou Li, on 2011-04-12 16:50,  wrote:
> Hi Joe,
> 
> Thanks for the code! That works for me pretty well.
> 
> Best,
> Leo
> 
> 
> On Mon, Apr 11, 2011 at 3:04 PM, Joe Louderback <jglouderback at gmail.com> wrote:
> > The following gives a 1-d vector reading the lower triangular values by row.
> >  There may be more efficient ways to do this, especially if you are
> > guaranteed there aren't any lower triangular elements equal to 0.
> > import numpy as np
def lowerTri(x):
     return np.concatenate([ x[i][:i+1] for i in xrange(x.shape[0]) ])
> > A = np.array([[2,  4,  6],[8, 10, 12], [14, 16, 18]])
> > lowerTri(A)
> > array([ 2, 8, 10, 14, 16, 18 ])
> >
> > -- Joe L.
> > On Mon, Apr 11, 2011 at 2:24 PM, Yiou Li <liyiou at gmail.com> wrote:
> >>
> >> Dear all,
> >>
> >> I have a N x N array and want to obtain the lower triangle half of the
> >> array elements and arrange them into a 1-dimensional data vector.
> >>
> >> I googled a bit and find the numpy.tril() function but it just zero
> >> out the upper triangle elements so it doesn't work for me. I also
> >> tried y = x(tril(x)!=0) but it gives me error.
> >>
> >> You advise is very much appreciated!
> >>
> >> Leo
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 198 bytes
Desc: Digital signature
URL: <http://mail.python.org/pipermail/baypiggies/attachments/20110412/eb7447a4/attachment.pgp>


More information about the Baypiggies mailing list