Python Pandas Count Interval Of Occurrence
I have implemented solution with iterating rows but it takes too long because of size of dataframe. The problem is this: I have a dataframe like this (ignore the first 3 columns):
Solution 1:
We can do that by writing a function that iterate the list (D). We go through the list, initialize a counter by 1, whenever we find one we increment, whenever we find 0, we affect the value and re-do the same process.
import pandas as pd
import copy
df = pd.DataFrame([1,1,1,0,1,1,0,0,0,1,1,1,0])
df.columns = ['D']
d= copy.copy(df.D)
deftransform(l):
count=1for index,x inenumerate(l):
if x==0:
l[index]=count
count=1else:
l[index]=0
count+=1return l
df['intervales']=transform(t)
df['D']=d
print df
The Output:
D intervales
0 1 0
1 1 0
2 1 0
3 0 4
4 1 0
5 1 0
6 0 3
7 0 1
8 0 1
9 1 0
10 1 0
11 1 0
12 0 4
I tried to do that using itertools, but it leads to treat many cases.
# import itertools# l= [list(g) for k,g in itertools.groupby(df.D,lambda x:x in [0]) ]
Post a Comment for "Python Pandas Count Interval Of Occurrence"