如何生成类似于以下的随机值列表:
X Y
0.2 0.8
0.1 0.9
0.6 0.4
0.3 0.7
x和y的总和应为= 1
答案 0 :(得分:2)
尝试使用pandas数据框sum
函数:
import pandas as pd
import numpy as np
import random
l = random.sample(list(np.arange(0.0,1.0,0.1)),4)
df = pd.DataFrame({'X': l,
'Y': ''})
df['Y'] = 1-df['X']
print(df.sum(axis=1))
输出:
0 1.0
1 1.0
2 1.0
3 1.0
dtype: float64
只需执行以下代码:
l = random.sample(list(np.arange(0.0,1.0,0.1)),4)
s = '\n'.join([str(x)+' '+str(y) for x,y in list(zip(l,[str(1-i) for i in l]))])
for i in s.splitlines():
print(sum([float(i) for i in i.split()]))
输出:
1.0
1.0
1.0
1.0