使用 numpy 将整数拆分为数字

2023-12-01

我有个问题。这个问题之前就被问过,但据我所知从未使用过 numpy。 我想将一个值拆分为不同的数字。做某事并返回一个数字。根据下面的问题我可以做我想做的事。 但我更喜欢在 numpy 中完成这一切。我希望它更有效,因为我不会来回更改 numpy 数组。 参见示例:

Example:

import numpy as np


l = np.array([43365644])  # is input array
n = int(43365644)
m = [int(d) for d in str(n)]
o = np.aslist(np.sort(np.asarray(m)))
p = np.asarray(''.join(map(str,o)))

我尝试过几次,但运气不佳。 我有一段时间使用了 split 函数,它工作了(在终端中),但将其添加到脚本后,它再次失败,我无法重现我之前所做的事情。

q = np.sort(np.split(l,1),axis=1)没有错误,但它仍然是单个值。

q = np.sort(np.split(l,8),axis=1)使用这种方法会出现以下错误:

Traceback (most recent call last):
File "python", line 1, in <module>
ValueError: array split does not result in an equal division

有什么方法可以在 numpy 中实现这一点吗?提前致谢

参考问题:
将单个数字转换为单个数字 Python
将整数列表转换为一个数字?


很简单:

  1. 将您的数字除以 1, 10, 100, 1000, ... 向下舍入
  2. 将结果除以 10

这产生

l // 10 ** np.arange(10)[:, None] % 10

或者如果您想要一个适用于的解决方案

  • any base
  • 任意数量的数字和
  • 任意数量的维度

你可以做

l = np.random.randint(0, 1000000, size=(3, 3, 3, 3))
l.shape
# (3, 3, 3, 3)

b = 10                                                   # Base, in our case 10, for 1, 10, 100, 1000, ...
n = np.ceil(np.max(np.log(l) / np.log(b))).astype(int)   # Number of digits
d = np.arange(n)                                         # Divisor base b, b ** 2, b ** 3, ...
d.shape = d.shape + (1,) * (l.ndim)                      # Add dimensions to divisor for broadcasting
out = l // b ** d % b

out.shape
# (6, 3, 3, 3, 3)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 numpy 将整数拆分为数字 的相关文章

随机推荐