Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the size of blocks of values in a list?

I have a list like this:

list_1 = [0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1]

How can I calculate the size of blocks of values of 1 and 0 in this list? The resulting list will look like :

list_2 = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 1, 1]
like image 325
NonSleeper Avatar asked Oct 25 '20 15:10

NonSleeper


People also ask

How do you find the size of a list?

Technique 1: The len() method to find the length of a list in Python. Python has got in-built method – len() to find the size of the list i.e. the length of the list. The len() method accepts an iterable as an argument and it counts and returns the number of elements present in the list.

How to count the size of a list in Python?

To get the length of a list in Python, you can use the built-in len() function. Apart from the len() function, you can also use a for loop and the length_hint() function to get the length of a list.

How do you print the length of each element in a list Python?

There is a built-in function called len() for getting the total number of items in a list, tuple, arrays, dictionary, etc. The len() method takes an argument where you may provide a list and it returns the length of the given list.


1 Answers

Try with cumsum with diff then transform count

s = pd.Series(list_1)
s.groupby(s.diff().ne(0).cumsum()).transform('count')
Out[91]: 
0     1
1     2
2     2
3     3
4     3
5     3
6     4
7     4
8     4
9     4
10    1
11    1
dtype: int64
like image 150
BENY Avatar answered Nov 02 '22 23:11

BENY