pandas - How to add random weights to list in Python? -


this question has answer here:

let's have list of countries investing in:

angola  croatia  denmark  germany ... 

how can randomize weights these countries add 100%, - looking run optimization test on investments:

angola  croatia  denmark  germany ... 1.3%    3.8%     4.6%     7.5%    ... (sum equals 100%) 

the logic behind randomization quite simple, wondering if there easy way it? current logic being, assign random number of them, take sum of randoms, take number assigned divided total.

how calculate these weights , add new row these weights using pandas dataframe? how set for-all statement?

it's possible achieve without using numpy or pandas. can generate n random numbers using random package , normalize them (divide each number sum of generated numbers). generate list of numbers in [0, 1] interval. if need scale them [0, 100] interval, multiply numbers 100.

example:

>>> import random >>> n = 10 >>> weights = [random.random() _ in range(n)] >>> sum_weights = sum(weights) >>> weights = [100*w/sum_weights w in weights] >>> print(weights) [9.341865975454088,  12.351871555212776,  11.613836128975514,  9.37242716105095,  7.74809967908834,  9.239611881353285,  5.432249328415935,  11.384334820466387,  13.436859772362507,  10.07884369762022] 

Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -