6

I have a large list containing values.

I would like to partition the list into sublists whose size is given in percentage, like 25%, 10%, 10%, 5%, %5, ..., %1% (these should add up to 100%), with respect to the size of the big list.

It seems there is no function like this.

0

1 Answer 1

6

You can use np.split like this:

import numpy as np

def splitPerc(l, perc):
    # Turn percentages into values between 0 and 1
    splits = np.cumsum(perc)/100.

    if splits[-1] != 1:
        raise ValueError("percents don't add up to 100")

    # Split doesn't need last percent, it will just take what is left
    splits = splits[:-1]

    # Turn values into indices
    splits *= len(l)

    # Turn double indices into integers.
    # CAUTION: numpy rounds to closest EVEN number when a number is halfway
    # between two integers. So 0.5 will become 0 and 1.5 will become 2!
    # If you want to round up in all those cases, do
    # splits += 0.5 instead of round() before casting to int
    splits = splits.round().astype(np.int)

    return np.split(l, splits)

list = np.arange(100)
percents = np.array([25, 10, 15,  5,  5,  5, 10, 25])
# 100 elements -> lengths of sublists should equal their percents
assert all(percents == map(len, splitPerc(list, percents)))
2
  • This solution may not work for some versions of NumPy, because splits[:-1]*len(l), in your case, ends up having floating-point numbers as indices, but split requires indices to be integers (at least for Python 3.5).
    – nbro
    Commented Oct 17, 2017 at 11:47
  • @nbro thanks for the hint. Numpy changed it's type-casting policy to being very restrictive since I wrote the answer.
    – swenzel
    Commented Oct 20, 2017 at 12:50

Not the answer you're looking for? Browse other questions tagged or ask your own question.