Skip to content Skip to sidebar Skip to footer

Python - Subtract A Number Of Samples From A Given In A Dictionary Structure

I have a dict structure with length 5. The dict structure is called 'mat_contents'. The information is located in 'traindata' and their respective labels in 'trainlabels'. I want t

Solution 1:

labels = [k for k, v in mat_contents.items() if v == 1]
result = np.random.choice(labels, 2, replace=False)

The first line extracts the relevant labels from your dictionary, and the second line chooses a random subset of 2 elements from these labels (without replacement), if numpy is imported as np.

Solution 2:

Can you not use a pandas data frame to do this? Link:Pandas Dataframe Sampling. This is an example that i have used in the past:

    import pandas as pd

    keeping = 0.8
    source = "/path/to/some/file"df = pd.DataFrame(source)

    ones = df[df.trainlabels == 1].sample(frac=keeping)
    twos = df[df.trainlabels == 2].sample(frac=keeping)

Post a Comment for "Python - Subtract A Number Of Samples From A Given In A Dictionary Structure"