簡體   English   中英

替換浮點數中的小數

[英]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) 不適用於十進制數。 有沒有辦法替換這些數字,或者是否應該重寫代碼以使其工作?

單獨生成每個數字位置的替代方案( 在線嘗試! ):

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 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM