英文:
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.
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
让我们将此分解为多个步骤。
- 使用
astype
方法将数组转换为布尔值。所有False
的列变成了0。 - 对数组使用NOT操作,将所有0的列从
False
转换为True
。 - 在轴1上使用
all
执行逻辑与操作,检查列是否全为0。 - 在轴0上使用
any
执行逻辑或操作,将结果折叠以获得数组中每列的True
或False
值。 - 使用结果的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.
- Use the
astype
method to convert the array to booleans. Columns of allFalse
are 0s. - Use NOT on the array to convert columns of 0s from
False
toTrue
. - Use
all
on axis 1 to perform a logical AND, which checks if a column is all 0s. - Use
any
on axis 0 to perform a logical OR, which collapses the result to getTrue
orFalse
values for each column in the array. - 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]]]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论