替换浮点数中的小数



这个平台上已经有人帮我生成了以下代码:

col,row = (100,1000) 
a = np.random.uniform(0,10,size=col*row).round(6).reshape(row,col)
mask = (a*1e6+1).astype(int)%10<2
a[mask] += 2e-6

这段代码确保最后一个小数不是0或9。但是,我希望生成的所有小数中没有0也没有9(这样就不可能有数字1.963749或3.459007)。

例如,将所有0和9替换为2(考虑到上面的示例,为1.263742和3.452227)是可以的。我知道函数replace(0,2)不适用于十进制数。是否有一种方法来替换这些数字,或者应该重写代码以使其工作?

单独生成每个数字位置的替代方法(在线尝试!):

a = sum(np.random.randint(1, 9, (row, col)) * 10**e
for e in range(-6, 1))

使用更多NumPy(在线试试!):

a = (np.random.randint(1, 9, (row, col, 7)) * [[10.**np.arange(-6, 1)]]).sum(2)

使用字符串的解决方案(我发现它不优雅,但它有效)。

假设此输入为pandas DataFramedf:

col1      col2
0  1.234567  9.999909
1  1.999999  0.120949

可以堆叠并替换为字符串:

def rand(x):
import random
return random.choice(list('12345678'))
df2 = (df
.stack()
.astype(str)
.str.replace(r'[09](?!.*.)', rand)
.astype(float)
.unstack()
)

输出:

col1      col2
0  1.234567  9.665236
1  1.184731  0.128345