是否有一种方法来生成一个(随机)数据集,该数据集是由具有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位的随机浮点数。然而,我不希望一个数据框被"填满"。小数点后2位,但数据帧中只有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)
输出:
{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],
}
NB。注意,数字将从到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)}
正好6位
您可以检查四舍五入的数字在小数点后第6位是否有零,在这种情况下可以添加任意数字。下面是一个例子,初始数据集:
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作为整数乘以并得到除的余数除以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])
使用DataFrame的示例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)
输出:
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)