Issue
i want to split dataframe when value of flag
column change to 1
df=pd.DataFrame({'A':[1,20,40,45,56,1,20,40,45,56],'flag':[3,2,4,1,1,3,3,1,1,1]})
Out[63]:
A flag
0 1 3
1 20 2
2 40 4
3 45 1
4 56 1
5 1 3
6 20 3
7 40 1
8 45 1
9 56 1
desired out:
print(group_1)
A flag
0 1 3
1 20 2
2 40 4
print(group_2)
A flag
0 1 3
1 20 3
Solution
You can use groupby
on the mask
ed DataFrame, with groups starting on each 1:
mask = df['flag'].eq(1)
groups = [g for _,g in df[~mask].groupby(mask.cumsum())]
output:
groups[0]
A flag
0 1 3
1 20 2
2 40 4
groups[1]
A flag
5 1 3
6 20 3
Answered By - mozway
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.