替换浮点数中的小数

Replace decimals in floating point numbers

本平台已经有人:

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) 不适用于十进制数。有没有办法替换这些数字,或者是否应该重写代码以使其工作?

使用字符串的解决方案(我发现它 non-elegant 但它有效)。

假设此输入为 pandas DataFrame df:

       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

单独生成每个数字位置的替代方案 (Try it online!):

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

使用更多 NumPy (Try it online!):

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