# Upper diagonal of a 2D numpy array

This seems simple (and is trivial to write a three-line loop for), but how can I use numpy slicing make a list of the index locations of the upper diagonal of a numpy array? I.e.

Given a 4x4 array, I'd like the index locations at the X's:

`[ X X X X ] [ 0 X X X ] [ 0 0 X X ] [ 0 0 0 X ] `

Giving:

`[ (0,0), (0,1), (0,2), (0,3), (1,1), (1,2), (1,3), (2,2), (2,3), (3,3) ] `

carnieri beat me to the `numpy.triu_indices` answer, but there is also `numpy.triu_indices_from` which takes an array as input rather than the dimensions.

Though the format of index locations is different, it seems like you want the function `numpy.triu_indices`.

`scipy.linalg.triu` and `nonzero`

If you're running Ubuntu and don't want to upgrade Numpy just for this, you can use the following function:

```from itertools import chain triu_indices = lambda x, y=0: zip(*list(chain(*[[(i, j) for j in range(i + y, x)] for i in range(x - y)]))) ```

Example:

`In [26]: triu_indices = lambda x, y=0: zip(*list(chain(*[[(i, j) for j in range(i + y, x)] for i in range(x - y)])))`

``` In [27]: triu_indices(4) Out[27]: [(0, 0, 0, 0, 1, 1, 1, 2, 2, 3), (0, 1, 2, 3, 1, 2, 3, 2, 3, 3)] ```

```In [28]: zip(*triu_indices(4)) Out[28]: [(0, 0), (0, 1), (0, 2), (0, 3), (1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)] ```

Category:python Views:0 Time:2010-12-14

## Related post

• Error when re-sizing data in numpy array 2010-12-01

I have two arrays that I want to re-size, but I also want to retain the original values. The code below re-sizes the arrays, but the problem is that it over-writes the original values, as you can see when you look at the output from the print(x) prin

• how to get correct order of the image when converted to numpy array? 2011-09-19

I am reading the image from the disk and I am converting it to a numpy array im=Image.open(infile) imdata = scipy.misc.fromimage(im) but the image is mirrored like it is stored on the disk. How to read it in a correct order. Thanks a lot. -----------

• Applying string operations to numpy arrays? 2011-11-11

Are there better ways to apply string operations to ndarrays rather than iterating over them? I would like to use a "vectorized" operation, but I can only think of using map (example shown) or list comprehensions. Arr = numpy.rec.fromrecords(zip(rang

• Elementwise multiply 1D-numpy arrays (shapes (k,1) or (k,)) and have result have the shape of the first 2012-04-22

I would like to implement a diagonal matrix apply function that is created by providing the diagonal d first, and then doing a bunch of matrix-vector multiplications with x. Of course I wouldn't want to create an actual matrix because all that's need

• Adding a dimension to every element of a numpy.array 2008-11-21

I'm trying to transform each element of a numpy array into an array itself (say, to interpret a greyscale image as a color image). In other words: >>> my_ar = numpy.array((0,5,10)) [0, 5, 10] >>> transformed = my_fun(my_ar) # In rea

• How do I build a numpy array from a generator? 2008-12-15

How can I build a numpy array out of a generator object? Let me illustrate the problem: >>> import numpy >>> def gimme(): ... for x in xrange(10): ... yield x ... >>> gimme() <generator object at 0x28a1758> >>

• deleting rows of a numpy array based on uniqueness of a value 2009-01-22

let's say I have a bi-dimensional array like that numpy.array( [[0,1,1.2,3], [1,5,3.2,4], [3,4,2.8,4], [2,6,2.3,5]]) I want to have an array formed eliminating whole rows based on uniqueness of values of last column, selecting the row to keep based o

• Best way to create a NumPy array from a dictionary? 2009-03-02

I'm just starting with NumPy so I may be missing some core concepts... What's the best way to create a NumPy array from a dictionary whose values are lists? Something like this: d = { 1: [10,20,30] , 2: [50,60], 3: [100,200,300,400,500] } Should turn

• Detect if a NumPy array contains at least one non-numeric value? 2009-05-26

I need to write a function which will detect if the input contains at least one value which is non-numeric. If a non-numeric value is found I will raise an error (because the calculation should only return a numeric value). The number of dimensions o

• Adding a field to a structured numpy array 2009-07-29

What is the cleanest way to add a field to a structured numpy array? Can it be done destructively, or is it necessary to create a new array and copy over the existing fields? Are the contents of each field stored contiguously in memory so that such c

• Definition of mathematical operations (sin-) on NumPy arrays containing objects 2009-10-07

I would like to provide "all" mathematical functions for the number-like objects created by a module (the uncertainties.py module, which performs calculations with error propagation)—these objects are numbers with uncertainties. What is the best way

• Incrementally building a numpy array and measuring memory usage 2009-10-07

I have a series of large text files (up to 1 gig) that are output from an experiment that need to be analysed in Python. They would be best loaded into a 2D numpy array, which presents the first question: As the number of rows is unknown at the begin

• Iterating over arbitrary dimension of numpy.array 2009-10-19

Is there function to get an iterator over an arbitrary dimension of a numpy array? Iterating over the first dimension is easy... In [63]: c = numpy.arange(24).reshape(2,3,4) In [64]: for r in c : ....: print r ....: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11

• How to delete columns in numpy.array 2009-10-29

I would like to delete selected columns in a numpy.array . This is what I do: n [397]: a = array([[ NaN, 2., 3., NaN], .....: [ 1., 2., 3., 9]]) In [398]: print a [[ NaN 2. 3. NaN] [ 1. 2. 3. 9.]] In [399]: z = any(isnan(a), axis=0) In [400]: print z

• String preallocation in numpy.arrays 2009-11-23

>>> import numpy as np >>> a = np.array(['zero', 'one', 'two', 'three']) >>> a[1] = 'thirteen' >>> print a ['zero' 'thirt' 'two' 'three'] >>> As you can see, the second element has been truncated to the ma

• efficient way to compress a numpy array (python) 2009-12-09

I am looking for an efficient way to compress a numpy array. I have an array like: dtype=[(name, (np.str_,8), (job, (np.str_,8), (income, np.uint32)] (my favourite example). if I'm doing something like this: my_array.compress(my_array['income'] >

• Euclidean distance between points in two different Numpy arrays, not within 2009-12-09

I have two arrays of x-y coordinates, and I would like to find the minimum Euclidean distance between each point in one array with all the points in the other array. The arrays are not necessarily the same size. For example: xy1=numpy.array( [[ 243,

• How can I "zip sort" parallel numpy arrays? 2009-12-14

If I have two parallel lists and want to sort them by the order of the elements in the first, it's very easy: >>> a = [2, 3, 1] >>> b = [4, 6, 2] >>> a, b = zip(*sorted(zip(a,b))) >>> print a (1, 2, 3) >>>

• How do I add rows and columns to a NUMPY array? 2009-12-15

Hello I have a 1000 data series with 1500 points in each. They form a (1000x1500) size Numpy array created using np.zeros((1500, 1000)) and then filled with the data. Now what if I want the array to grow to say 1600 x 1100? Do I have to add arrays us