使用numpy将整数拆分为数字 [英] Split integer into digits using numpy
问题描述
我有一个问题.有人问过这个问题,但据我所见,从未使用过numpy. 我想将值分割成不同的数字.做些事情,然后返回一个数字.根据以下问题,我可以做我想做的事. 但是我更喜欢用numpy来做.我希望它会更高效,因为我不会前后更改为numpy数组. 参见示例:
I have a question. The question is asked before but as far as i can see never using numpy. I want split a value in the different digits. do somthing and return back into a number. based on the questions below i can do what i want. But i prefere to do it all in numpy. I expect it is more efficient because i'm not changing back and forward to numpy arrays. See 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函数,它在终端中起作用了,但是将其添加到脚本中后又失败了,而且我无法重现以前的工作.
I have tried serval times but without much luck. I had one moment i used the split function and it worked (in the terminal) but after add it to a script it failed again and i was unable to reproduce what i did before..
q = np.sort(np.split(l,1),axis=1)
没有错误,但仍然是一个单一的值.
q = np.sort(np.split(l,1),axis=1)
no error but it is still a singel value.
q = np.sort(np.split(l,8),axis=1)
使用此方法会产生以下错误:
q = np.sort(np.split(l,8),axis=1)
With this method it gives the following error:
Traceback (most recent call last):
File "python", line 1, in <module>
ValueError: array split does not result in an equal division
是否有某种方式可以在numpy中实现?预先感谢
Is there some way that this is possible in numpy? thanks in advance
参考问题:
将单个数字转换为单个数字Python
将整数列表转换为一个数字吗?
referenced questions:
Turn a single number into single digits Python
Convert list of ints to one number?
推荐答案
非常简单:
- 将您的电话号码除以1,10,100,1000,...四舍五入
- 将结果乘以10
产生
l // 10 ** np.arange(10)[:, None] % 10
或者如果您想要一个适用的解决方案
Or if you want a solution that works for
- 任何基地
- 任意数量的数字和
- 任意数量的尺寸
你可以做
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)
这篇关于使用numpy将整数拆分为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!