gpt4 book ai didi

python - 将 numpy 数组分解为二进制数组

转载 作者:太空宇宙 更新时间:2023-11-04 10:36:43 25 4
gpt4 key购买 nike

我有一个 numpy 数组

[0 0 0 0 0 0 0 1 1 2 2 2 2 2 1 1 0 0 0 0 0 0 0 0]

我想转换/溶解成

[[0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0]]

我目前的做法是首先使用 while 循环将数组拆分为 1,然后根据 np.where(x>0) 创建一个数组.然而,我认为这不是最有效和优雅的 numpy 解决方案。关于如何改进这一点的任何想法?

source = np.array([0., 0., 0., 0., 0., 0., 0., 1., 1., 2., 2., 2., 2.,
2., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0.], dtype=np.int)

diss = None
while np.any(source):
row = np.greater(source, 0).astype(np.int)
if diss is None:
diss = row
else:
diss = np.vstack([diss, row])
source -= row

idx = np.where(diss > 0)
result = np.zeros((0,source.shape[0]), dtype=np.int)
for x, y in zip(*idx):
row = np.zeros(source.shape, dtype=np.int)
row[y] = 1
result = np.vstack([result, row])

最佳答案

这是一种方法:

In [38]: x = np.array([0,0,0,0,0,1,1,2,2,2,1,1,0,0])

In [39]: n = x.sum()

In [40]: rows = np.arange(n)

In [41]: positions = np.nonzero(x)[0]

In [42]: cols = np.repeat(positions, x[positions])

In [43]: result = np.zeros((n, len(x)), dtype=int)

In [44]: result[rows, cols] = 1

In [45]: result
Out[45]:
array([[0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0]])

关于python - 将 numpy 数组分解为二进制数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22908475/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com