mercredi 13 mai 2020

Iteratively Sample from a list Until a Condition is Met - Python

I have a list of values:

address_ids = [123,123,123,123,456,789,112,115]

From address_ids list I want to check what percentage of single value attributing to the whole list.

I am looking at it this way,

unique_adres = list(set(address_ids))

save_vals = {}
for i in unique_adres:
    temp_val =  address_ids.count(i)/len(address_ids)
    save_vals[i] = temp_val  
save_vals
>> {456: 0.125, 112: 0.125, 115: 0.125, 789: 0.125, 123: 0.5}

123 has 50 percent. I need to have a condition if a single value has more than 50% of the data, then I want to resample with replacement and 8 samples in which a single attribute does not contribute 50% of whole list. Therefore, it will look something like this, (since random smapling, this won't be exactly same) and the idea is making a single attribute does not contribute 50% of the whole list.

>> {456: 0.125, 112: 0.125, 115: 0.125, 789: 0.225, 123: 0.4}

OR

>> {456: 0.125, 112: 0.225, 115: 0.125, 789: 0.225, 123: 0.3}

I tried something like this,

from random import choices
for k,v in save_vals.items():
    if v >= 0.50:
        break
    choices_vals = choices(address_ids, k=8)

But not sure, how to continuously check my condition with resamples if it doesn't meet the condition if v >= 0.50:.

Any help or suggestion would be great.




Aucun commentaire:

Enregistrer un commentaire