플래그 열에 모든 1이 있을 때 dataframe에서 그룹을 가져오고 크기가 2보다 큰 그룹을 유지하는 방법

Asked 1 years ago, Updated 1 years ago, 250 views

플래그가 1인 그룹을 추출하고 크기가 2보다 크면 그룹을 유지했으면 합니다.

df2=pd.DataFrame({'A':[1,20,40,45,56,1,20,40,45,56],'flag':[3,2,4,1,1,3,3,1,1,1]})
print(df2)
    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

output
7  40     1
8  45     1
9  56     1

python

2022-06-21 10:54

2 Answers

여러 가지 해결방법이 있습니다.

pandas에서 groupby와 같은 걸 사용하거나 단순히 아래 내용을 사용해도 가능합니다.

print(df2[(df2['flag']==1) & (df2['A']>2)])


2022-06-21 10:56

pandas.DataFrame.groupby를 쓰면 되겠네요.

s = df2["flag"].eq(1)
m = s.diff(1).ne(0).cumsum()
new_df = df2[s.groupby(m).transform(lambda x: x.sum()>2)]

 

결과

    A  flag
7  40     1
8  45     1
9  56     1 


2022-06-21 10:56

If you have any answers or tips


© 2023 OneMinuteCode. All rights reserved.