[英]how to eliminate rows with continuous values for a column using python/pandas
我在第1列中有一個這樣的數據框,其中有連續的零:
col1 col2 col3
1 2 3
0 4 5
0 1 4
2 7 8
0 1 2
4 4 4
0 1 3
0 4 2
0 1 9
4 6 2
我想跳過至少連續2次連續零的行。
例如,輸出將如下所示:
col1 col2 col3
1 2 3
2 7 8
0 1 2
4 4 4
4 6 2
采用:
m = df['col1'].ne(0)
s = m.cumsum() * (~m)
df = df[s.groupby(s).transform('size').lt(2) | m]
要么:
df = df[s.map(s.value_counts()).lt(2) | m]
print (df)
col1 col2 col3
0 1 2 3
3 2 7 8
4 0 1 2
5 4 4 4
9 4 6 2
說明 :
首先通過Series.ne
比較不等於0
的Series.ne
:
print (df['col1'].ne(0))
0 True
1 False
2 False
3 True
4 False
5 True
6 False
7 False
8 False
9 True
Name: col1, dtype: bool
然后將cumsum
用於組-值為0
組具有相同的組:
print (m.cumsum())
0 1
1 1
2 1
3 2
4 2
5 3
6 3
7 3
8 3
9 4
Name: col1, dtype: int32
布爾布爾掩碼的倒數的倍數,用於刪除非0
值:
print (m.cumsum() * (~m))
0 0
1 1
2 1
3 0
4 2
5 0
6 3
7 3
8 3
9 0
Name: col1, dtype: int32
然后通過GroupBy.transform
獲取組GroupBy.transform
:
print (s.groupby(s).transform('size'))
0 4
1 2
2 2
3 4
4 1
5 4
6 3
7 3
8 3
9 4
Name: col1, dtype: int64
並按lt
<
進行比較:
print (s.groupby(s).transform('size').lt(2))
0 False
1 False
2 False
3 False
4 True
5 False
6 False
7 False
8 False
9 False
Name: col1, dtype: bool
由原始蒙版最后的鏈m
by |
對於按位OR
:
print (s.groupby(s).transform('size').lt(2) | m)
0 True
1 False
2 False
3 True
4 True
5 True
6 False
7 False
8 False
9 True
Name: col1, dtype: bool
最后一個通過boolean indexing
過濾器:
print (df[s.groupby(s).transform('size').lt(2) | m])
col1 col2 col3
0 1 2 3
3 2 7 8
4 0 1 2
5 4 4 4
9 4 6 2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.