Finding all 1-d arrays within a numpy array

Given a numpy array of dimension n with each direction having length m, I would like to iterate through all 1-dimensional arrays of length m.

For example, consider:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import numpy as np
x = np.identity(4)
array([[1., 0., 0., 0.],
[0., 1., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.]])
</code>
<code>import numpy as np x = np.identity(4) array([[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]) </code>
import numpy as np
x = np.identity(4)
array([[1., 0., 0., 0.],
       [0., 1., 0., 0.],
       [0., 0., 1., 0.],
       [0., 0., 0., 1.]])

then I would like to find all all 1-dimensional arrays with length 4. So the result should include all 4 rows, all 4 columns, and the 2 diagonals:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>[x[i,:] for i in range(4)] + [x[:,i] for i in range(4)] + [np.array([x[i,i] for i in range(4)])] + [np.array([x[3-i,i] for i in range(4)])]
</code>
<code>[x[i,:] for i in range(4)] + [x[:,i] for i in range(4)] + [np.array([x[i,i] for i in range(4)])] + [np.array([x[3-i,i] for i in range(4)])] </code>
[x[i,:] for i in range(4)] + [x[:,i] for i in range(4)] + [np.array([x[i,i] for i in range(4)])] + [np.array([x[3-i,i] for i in range(4)])]

It’s unclear to me how to generalize this to higher dimensional arrays since the position of the “:” in the slice needs to iterate as well. In a higher dimensional analogue with

slices = [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]

we can get

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>[x[i,j,:] for (i,j) in slices]
</code>
<code>[x[i,j,:] for (i,j) in slices] </code>
[x[i,j,:] for (i,j) in slices]

but then I’m not sure how to proceed to iterate through the permutations of [i,j,:].

4

Although the comprehensions are readable, for large arrays you probably want to use what numpy gives you:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import numpy as np
n = 4
# random n*n numpy array
arr = np.random.rand(n, n)
print(arr)
# this has all the data you need, relatively efficiently - but not in 1D shape
result = (
np.vsplit(arr, n) +
np.hsplit(arr, n) +
[arr.diagonal()] +
[arr[np.arange(n), np.arange(n - 1, -1, -1)]]
)
# you can just flatten them as you used them:
for xs in result:
print(xs.ravel())
# or flatten them into a new result:
result_1d = [xs.ravel() for xs in result]
</code>
<code>import numpy as np n = 4 # random n*n numpy array arr = np.random.rand(n, n) print(arr) # this has all the data you need, relatively efficiently - but not in 1D shape result = ( np.vsplit(arr, n) + np.hsplit(arr, n) + [arr.diagonal()] + [arr[np.arange(n), np.arange(n - 1, -1, -1)]] ) # you can just flatten them as you used them: for xs in result: print(xs.ravel()) # or flatten them into a new result: result_1d = [xs.ravel() for xs in result] </code>
import numpy as np

n = 4
# random n*n numpy array
arr = np.random.rand(n, n)
print(arr)

# this has all the data you need, relatively efficiently - but not in 1D shape
result = (
    np.vsplit(arr, n) +
    np.hsplit(arr, n) + 
    [arr.diagonal()] +
    [arr[np.arange(n), np.arange(n - 1, -1, -1)]]
)

# you can just flatten them as you used them:
for xs in result:
    print(xs.ravel())

# or flatten them into a new result:
result_1d = [xs.ravel() for xs in result]

Edit: user @Matt correctly pointed out in the comments that this solution only works for the case of a 2-dimensional array.

Things get a bit more complicated for an arbitrary number of dimensions n with size m across all dimensions. This works, but given the complexity, can probably be improved upon for simplicity:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import numpy as np
import itertools as it
# random n*n numpy array
m = 2
n = 3
arr = np.random.rand(*([m] * n))
print(arr)
def get_all_lines(arr):
ndim = arr.ndim
size = arr.shape[0] # assuming the same size for all dimensions
# generate each 1d slice along and across each axis
for fixed in it.product(range(size), repeat=ndim - 1):
for axis in range(ndim):
yield arr[fixed[:axis] + (slice(None, ),) + fixed[axis:]]
# generate each 1d diagonal for each combination of axes
for d_dim in range(2, ndim+1): # d_dim is the number of varying axes
for fixed in it.product(range(size), repeat=(ndim - d_dim)): # fixed indices for the other axes
of, od = 0, 0 # offsets for accessing fixed values and directions
# each varying axis can be traversed in one of two directions
for d_tail in it.product((0, 1), repeat=d_dim - 1): # dir is the direction for each varying axis
d = (1, *d_tail)[::-1] # deduplicate and reverse the direction
for axes in it.combinations(range(ndim), d_dim): # axes to vary
fm = d_dim * (d_dim + 1) // 2 - sum(axes) # first dimension with a fixed index
dm = min(axes) # first dimension with a varying index
yield [
arr[*[fixed[of := 0 if j == fm else of + 1]
if j not in axes else
(i if d[od := 0 if j == dm else od + 1] else size - (i + 1))
for j in range(ndim)]] for i in range(size)
]
lines = get_all_lines(arr)
for line in lines:
print(line)
</code>
<code>import numpy as np import itertools as it # random n*n numpy array m = 2 n = 3 arr = np.random.rand(*([m] * n)) print(arr) def get_all_lines(arr): ndim = arr.ndim size = arr.shape[0] # assuming the same size for all dimensions # generate each 1d slice along and across each axis for fixed in it.product(range(size), repeat=ndim - 1): for axis in range(ndim): yield arr[fixed[:axis] + (slice(None, ),) + fixed[axis:]] # generate each 1d diagonal for each combination of axes for d_dim in range(2, ndim+1): # d_dim is the number of varying axes for fixed in it.product(range(size), repeat=(ndim - d_dim)): # fixed indices for the other axes of, od = 0, 0 # offsets for accessing fixed values and directions # each varying axis can be traversed in one of two directions for d_tail in it.product((0, 1), repeat=d_dim - 1): # dir is the direction for each varying axis d = (1, *d_tail)[::-1] # deduplicate and reverse the direction for axes in it.combinations(range(ndim), d_dim): # axes to vary fm = d_dim * (d_dim + 1) // 2 - sum(axes) # first dimension with a fixed index dm = min(axes) # first dimension with a varying index yield [ arr[*[fixed[of := 0 if j == fm else of + 1] if j not in axes else (i if d[od := 0 if j == dm else od + 1] else size - (i + 1)) for j in range(ndim)]] for i in range(size) ] lines = get_all_lines(arr) for line in lines: print(line) </code>
import numpy as np
import itertools as it

# random n*n numpy array
m = 2
n = 3
arr = np.random.rand(*([m] * n))
print(arr)


def get_all_lines(arr):
    ndim = arr.ndim
    size = arr.shape[0]  # assuming the same size for all dimensions
    # generate each 1d slice along and across each axis
    for fixed in it.product(range(size), repeat=ndim - 1):
        for axis in range(ndim):
            yield arr[fixed[:axis] + (slice(None, ),) + fixed[axis:]]
    # generate each 1d diagonal for each combination of axes
    for d_dim in range(2, ndim+1):  # d_dim is the number of varying axes
        for fixed in it.product(range(size), repeat=(ndim - d_dim)):  # fixed indices for the other axes
            of, od = 0, 0  # offsets for accessing fixed values and directions
            # each varying axis can be traversed in one of two directions
            for d_tail in it.product((0, 1), repeat=d_dim - 1):  # dir is the direction for each varying axis
                d = (1, *d_tail)[::-1]  # deduplicate and reverse the direction
                for axes in it.combinations(range(ndim), d_dim):  # axes to vary
                    fm = d_dim * (d_dim + 1) // 2 - sum(axes)  # first dimension with a fixed index
                    dm = min(axes)  # first dimension with a varying index
                    yield [
                        arr[*[fixed[of := 0 if j == fm else of + 1]
                              if j not in axes else
                              (i if d[od := 0 if j == dm else od + 1] else size - (i + 1))
                              for j in range(ndim)]] for i in range(size)
                    ]


lines = get_all_lines(arr)
for line in lines:
    print(line)

The mentioned “deduplication” avoids including each diagonal twice (once in both directions).

Also note that this yields 1d arrays as well as lists of numbers, you can of course cast these appropriately.

6

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật