Given a N-dimensional array, get all combinations of subarrays locking (N-1) dimensions and leaving one free

huangapple go评论54阅读模式
英文:

Given a N-dimensional array, get all combinations of subarrays locking (N-1) dimensions and leaving one free

问题

假设我们有一个形状为(10, 20, 30)的数组

我想要获取的是

1) 形状为(10)的20*30数组
2) 形状为(20)的10*30数组
3) 形状为(30)的10*20数组

手动锁定除一维外的所有维度很容易但我在编写一个有效的循环来以这种方式迭代时遇到了困难原因是在我的应用场景中我将有几个维度的变化范围在2到5之间我需要获取锁定除一维外的所有维度的所有子数组

我曾经以为可以使用转置和滚动创建一个滚动的索引例如

```python
data = np.zeros((10, 20, 30))
for ndim in range(len(data.shape)):
   index = np.arange(0, len(data.shape)), 1)
   index = np.roll(index, 1)
   _data = np.transpose(data, index)[0]

然后我意识到这是无用的,因为它与我需要的相反。

我甚至尝试向ChatGPT询问。所以现在是寻求帮助的时候了。我完全被卡住了。


<details>
<summary>英文:</summary>

Suppose there we have an array of shape(10, 20, 30).

What I would like to get are all the:

1) 20*30 arrays of shape(10),
2) 10*30 arrays of shape(20), 
3) 10*20 arrays of shape(30).

Locking all dimensions but one manually is easy, but I am struggling to write an efficient loop to iterate this way. The reason for this is that in my application case, I will have several dimensions which will vary between 2 to 5, and I will need to get all subarrays of locking all dimensions but one.


I thought I could use transpose and roll to create an index which rolls, such as 



data = np.zeros((10, 20, 30))
for ndim in range(len(data.shape)):
index = np.arange(0, len(data.shape)), 1)
index = np.roll(index, 1)
_data = np.transpose(data, index)[0]

  
... and then I realized this is useless, because its the opposite of what I need.

I got to the point I even tried asking chatgpt. So it&#39;s time to ask for help. I am utterly stuck

</details>


# 答案1
**得分**: 0

```python
我不完全确定您具体需要什么,但也许是这样的?
```python
for i in range(data.ndim):
    data2 = np.moveaxis(data, i, 0)
    for index in np.ndindex(data2.shape[1:]):
        print(data2[..., index])
英文:

I'm not totally sure exactly what you're asking for, but perhaps it's something like this?

for i in range(data.ndim):
    data2 = np.moveaxis(data, i, 0)
    for index in np.ndindex(data2.shape[1:]):
        print(data2[..., index])

This code moves each axis in data to the first axis, and then loops over the remaining two dimensions.

huangapple
  • 本文由 发表于 2023年2月24日 01:43:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75548446.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定