[SciPy-User] Can I get the "rings" of a 2D array?
josef.pktd@gmai...
josef.pktd@gmai...
Mon Apr 12 22:19:02 CDT 2010
On Mon, Apr 12, 2010 at 10:23 PM, Jeremy Conlin <jlconlin@gmail.com> wrote:
> On Mon, Apr 12, 2010 at 5:16 PM, Charles R Harris
> <charlesr.harris@gmail.com> wrote:
>>
>>
>> On Mon, Apr 12, 2010 at 4:55 PM, Jeremy Conlin <jlconlin@gmail.com> wrote:
>>>
>>> I need to get the "rings" of a 2D array; i.e. the first ring would be
>>> the first and last column in addition to the first and last row, the
>>> second ring would be the second and second-from-last row and the
>>> second and second-from-last column---except for what is not in the
>>> first ring. Is there a way to slice an array to get this data?
>>>
>>
>> So will the rings be different sizes or all the same size with the other
>> elements zeroed?
>
> Good question. The better option would be to keep the size of the
> array the same and zero all the other elements.
The following seems to work for building the index arrays for the rings,
tested on only 2 examples
import numpy as np
a = np.arange(30).reshape(6,5)
n = np.array(a.shape)
from collections import defaultdict
rings = defaultdict(list)
for i in np.ndindex(*n):
#print i,
imin = min(i)
imax = min(n-i-1)
#print imin,imax
rings[min(imin,imax)].append(i)
for r in rings:
print r
print a[np.array(rings[r])[:,0],np.array(rings[r])[:,1]]
0
[ 0 1 2 3 4 5 9 10 14 15 19 20 24 25 26 27 28 29]
1
[ 6 7 8 11 13 16 18 21 22 23]
2
[12 17]
>>> a
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24],
[25, 26, 27, 28, 29]])
Josef
>
> Jeremy
> _______________________________________________
> SciPy-User mailing list
> SciPy-User@scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
>
More information about the SciPy-User
mailing list