Python - assign increasing class to list val based on mean

Viewed 38

I have the following problem: having a list of values, let's say:

x = [1000, 950, 860, 1120, 430, 270, 0, 15, 0, 26, 278, 0, 950, 1020, 980, 1040, 670, 540, 820, 0, 0, 0, 190, 270, 479, 1247]

I calculate the mean val:

mean = np.mean(x)
# 505.96

Now I would like to calculate a list, where a value is assigned (starting from 1) to each item of list x, that if the item is higher than mean, then it assigns one (same) value until the relation its shifted (lower than mean), then it assigns the second val, and so on. So for the example x list, the output is as follows:

x = [1000, 950, 860, 1120, 430, 270, 0, 15, 0, 26, 278, 0, 950, 1020, 980, 1040, 670, 540, 820, 0, 0, 0, 190, 270, 479, 1247]
#   [1,    1,   1,   1,    2,   2,   2, 2,  2, 2,  2,   2, 3,   3,    3,   3,    3,   3,   3,   4, 4, 4, 4,   4,   4,   5   ]

Thanks

2 Answers

You can take np.diff on the result of the comparisson with the mean to see when the "shifts" occur. Then take the np.cumsum to increment the values:

np.cumsum(np.diff(x>mean, prepend=False))
array([1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4,
       4, 4, 4, 5], dtype=int32)

You can try in this way apart from the another answer:

mean = np.mean(x)
out = []
if out[0]>mean:
    cur  = 'high' 
app = 1
for i in x:
    if i>mean and cur=='high' or (i<mean and cur=='low') :
        out.append(app)
    elif i<mean and cur=='high':
        cur = 'low'
        app += 1
        out.append(app)
    elif i>mean and cur=='low':
        cur = 'high'
        app += 1
        out.append(app)
print(out)
Related