[英]Generate random numbers between a range with only two decimal points in python
[英]Generate a dataset with only 6 decimal numbers
有沒有辦法生成一個(隨機)數據集,該數據集填充有 6 位小數和小數點分隔符前 1 位數字的值?
所以例如像這樣:
"A":[5.398811, 2.232098, 9.340909, 3.343434],
"B":[6.436293,5.293756, 1.235937, 1.987384],
"C": [3.572831, 3.826355, 3.827264, 3.257321]
我發現 round(random.uniform(33.33, 66.66), 2) 返回一個隨機浮點數,最多 2 位小數。 但是,我不希望 dataframe 填充“最多”2 位小數,但 dataframe 只填充 6 位小數。 我想要大約 1000 行和 100 列。
編輯:在任何小數點中沒有任何 0 或 9 也很好。 這是因為我正在研究四舍五入的小數點。 當將 1.999999 舍入到 5 位小數時,將得到 2.00000,即 2。這樣就不會給出可靠的舍入結果。 不知道在多大程度上這實際上是可行的。
您可以使用numpy.random.uniform
提高效率,然后轉換為字典:
import numpy as np
col,row = (10,20) # (100, 1000) in your case
out = dict(enumerate(np.random.uniform(0,10,size=col*row)
.round(6).reshape(row,col).tolist()))
print(out)
output:
{0: [5.488135, 7.151894, 6.027634, 5.448832, 4.236548, 6.458941, 4.375872, 8.91773, 9.636628, 3.834415],
1: [7.91725, 5.288949, 5.680446, 9.255966, 0.710361, 0.871293, 0.202184, 8.326198, 7.781568, 8.700121],
2: [9.786183, 7.991586, 4.614794, 7.805292, 1.182744, 6.39921, 1.433533, 9.446689, 5.218483, 4.146619],
...
19: [3.982211, 2.098437, 1.86193, 9.443724, 7.395508, 4.904588, 2.274146, 2.543565, 0.580292, 4.344166],
}
注意。 請注意,數字最多為 6 位小數(例如,0.123400 將顯示為0.1234 ,否則會產生非隨機偏差
純 python 版本(效率較低):
import random
out = {i: [round(random.uniform(0, 10), 6) for j in range(100)]
for i in range(1000)}
您可以檢查四舍五入的數字是否在小數點后第六位為零,在這種情況下添加一個任意數字。 這是一個示例,初始數據集:
np.random.seed(0) # for reproducibility
a = np.random.uniform(0, 10, size=20).round(6)
array([5.488135, 7.151894, 6.027634, 5.448832, 4.236548, 6.458941,
4.375872, 8.91773 , 9.636628, 3.834415, 7.91725 , 5.288949,
5.680446, 9.255966, 0.710361, 0.871293, 0.202184, 8.326198,
7.781568, 8.700121])
更正:
np.random.seed(0) # for reproducibility
a = np.random.uniform(0, 10, size=20).round(6)
# identify numbers ending in 0
mask = (a*1e6).astype(int)%10==0
# add a terminal 1
a[mask] += 1e-6
a
array([5.488135, 7.151894, 6.027634, 5.448832, 4.236548, 6.458941,
4.375872, 8.917731, 9.636628, 3.834415, 7.917251, 5.288949,
5.680446, 9.255966, 0.710361, 0.871293, 0.202184, 8.326198,
7.781568, 8.700121])
這通過將 1e6 乘以 integer 並將余數除以 10 來實現:
(a*1e6).astype(int)%10
array([5, 4, 4, 2, 8, 1, 2, 0, 8, 5, 0, 9, 6, 6, 1, 3, 4, 8, 8, 1])
import numpy as np
col,row = (4,5) # (100, 1000) in your case
a = np.random.uniform(0,10,size=col*row).round(6).reshape(row,col)
mask = (a*1e6+1).astype(int)%10<2
# add a terminal 1
a[mask] += 2e-6
df = pd.DataFrame(a)
print(df)
Output:
0 1 2 3
0 5.488135 7.151894 6.027634 5.448832
1 4.236548 6.458941 4.375872 8.917732
2 9.636628 3.834415 7.917252 5.288951
3 5.680446 9.255966 0.710361 0.871293
4 0.202184 8.326198 7.781568 8.700121
也許嘗試生成從 1,000,000 到 9,999,999 的數字,然后除以 1,000,000。 這將確保數字始終正好是 6 位小數。
關於第二個條件,您可以通過轉換為字符串來檢查數字,例如:
if '9' in str(the_number):
continue
else:
result.append(the_number)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.