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]
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With