[Numpy-discussion] Functions for indexing into certain parts of an array (2d)
Keith Goodman
kwgoodman@gmail....
Sat Jun 6 13:46:52 CDT 2009
On Sat, Jun 6, 2009 at 11:30 AM, Fernando Perez <fperez.net@gmail.com> wrote:
> On Sat, Jun 6, 2009 at 12:09 AM, Robert Kern<robert.kern@gmail.com> wrote:
>> diag_indices() can be made more efficient, but these are fine.
>
> Suggestion? Right now it's not obvious to me...
I'm interested in a more efficient way too. Here's how I plan to adapt
the code for my personal use:
def fill_diag(arr, value):
if arr.ndim != 2:
raise ValueError, "Input must be 2-d."
idx = range(arr.shape[0])
arr[(idx,) * 2] = value
return arr
>> a = np.array([[1,2,3],[4,5,6],[7,8,9]])
>> a = fill_diag(a, 0)
>> a
array([[0, 2, 3],
[4, 0, 6],
[7, 8, 0]])
>> a = fill_diag(a, np.array([1,2,3]))
>> a
array([[1, 2, 3],
[4, 2, 6],
[7, 8, 3]])
More information about the Numpy-discussion
mailing list