ratchet
ratchet

Reputation: 195

Apply Pareto probabilities to n items in Python

Given a list in sorted order:

countries = ['USA', 'GB', 'RU', 'CN']

How would I assign np.pareto probabilities to each item in countries? The total probability should be no greater than 1.0

Desired outcome:

countries = [{
              {"name": "USA",
               "power": 0.24},
              {...}
             }]

I would later access the data like so:

np.random.choice(countries[name], p=countries[power])

Upvotes: 1

Views: 287

Answers (1)

Jeremy McGibbon
Jeremy McGibbon

Reputation: 3785

You need a shape parameter for np.random.pareto, and I'd assume you just want a list of dictionaries, and not a list containing one set containing dictionaries. This might be what you're looking for:

import numpy as np

countries = ['USA', 'GB', 'RU', 'CN']
pareto_shape = 1.

prob = np.random.pareto(pareto_shape, len(countries))
prob /= np.sum(prob)

out_list = []
for p, country in zip(prob, countries):
    out_list.append({
        'name': country,
        'power': p,
    })
print(out_list)

At least, that would give you something that looks like

[
    {"name": "USA",
     "power": 0.24},
    {...}
]

But if you want to access data using np.random.choice, what you really want to use is

import numpy as np

countries = ['USA', 'GB', 'RU', 'CN']
pareto_shape = 1.

prob = np.random.pareto(pareto_shape, len(countries))
prob /= np.sum(prob)

print(np.random.choice(countries, p=prob))

Upvotes: 2

Related Questions