如何从一个三维数组中移除全零列,而不减少维度?

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

How can I remove an all-zero column from a 3D array without reducing the dimensions

问题

我尝试使用NumPy从3D数组中移除所有零列,同时保持维度数量。我不想使用trim,因为列可能不在数组的边缘。

预期功能

我尝试使用~np.all,但似乎会去掉一个维度:

import numpy as np

vals = [1,0,3,4,0,6,7,8,9,10,11,12]
array = np.reshape(vals, (2,2,3))

数组:

[[[ 1  0  3]
  [ 4  0  6]]

 [[ 7  8  9]
  [10 11 12]]]

这是我想要看到的:

[[[ 1  3]
  [ 4  6]]

 [[ 7  9]
  [10 12]]]
英文:

I'm trying to remove an all-zero column from a 3D array using numpy while maintaining the number of dimensions. I don't want to use trim either as the columns might not be at the edges of the array.

Intended functionality

I tried using ~np.all but that seems to strip away one of the dimensions:

import numpy as np

vals = [1,0,3,4,0,6,7,8,9,10,11,12]
array = np.reshape(vals, (2,2,3))

array:

[[[ 1  0  3]
  [ 4  0  6]]

 [[ 7  8  9]
  [10 11 12]]]

This is what I want to see:

[[[ 1  3]
  [ 4  6]]

 [[ 7  9]
  [10 12]]]

答案1

得分: 0

让我们将此分解为多个步骤。

  1. 使用astype方法将数组转换为布尔值。所有False的列变成了0。
  2. 对数组使用NOT操作,将所有0的列从False转换为True
  3. 在轴1上使用all执行逻辑与操作,检查列是否全为0。
  4. 在轴0上使用any执行逻辑或操作,将结果折叠以获得数组中每列的TrueFalse值。
  5. 使用结果的NOT版本索引数组的最后一个轴,只获取没有0的列。

带有标签的步骤:

import numpy as np

vals = [1, 0, 3, 4, 0, 6, 7, 8, 9, 10, 11, 12]
array = np.reshape(vals, (2, 2, 3))
step1 = array.astype(bool)
step2 = ~step1
step3 = step2.all(1)
step4 = step3.any(0)
step5 = array[..., ~step4]

全部合在一起:

vals = [1, 0, 3, 4, 0, 6, 7, 8, 9, 10, 11, 12]
array = np.reshape(vals, (2, 2, 3))
res = array[..., ~(~array.astype(bool)).all(1).any(0)]
print(res)

输出:

[[[ 1  3]
  [ 4  6]]

 [[ 7  9]
  [10 12]]]
英文:

Let's break this up into multiple steps.

  1. Use the astype method to convert the array to booleans. Columns of all False are 0s.
  2. Use NOT on the array to convert columns of 0s from False to True.
  3. Use all on axis 1 to perform a logical AND, which checks if a column is all 0s.
  4. Use any on axis 0 to perform a logical OR, which collapses the result to get True or False values for each column in the array.
  5. Use the NOT version of the result to index the last axis of the array to only get the columns that don't have the 0.

With labeled steps:

import numpy as np

vals = [1, 0, 3, 4, 0, 6, 7, 8, 9, 10, 11, 12]
array = np.reshape(vals, (2, 2, 3))
step1 = array.astype(bool)
step2 = ~step1
step3 = step2.all(1)
step4 = step3.any(0)
step5 = array[..., ~step4]

All together:

vals = [1, 0, 3, 4, 0, 6, 7, 8, 9, 10, 11, 12]
array = np.reshape(vals, (2, 2, 3))
res = array[..., ~(~array.astype(bool)).all(1).any(0)]
print(res)

Output:

[[[ 1  3]
  [ 4  6]]

 [[ 7  9]
  [10 12]]]

huangapple
  • 本文由 发表于 2023年6月26日 22:41:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76557735.html
匿名

发表评论

匿名网友

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

确定