![](/img/trans.png)
[英]What is the best way to remove rows in Pandas DF after a certain value?
[英]Best way to remove rows that have more of a certain value than a given amount (numpy)
我創建了一個列大小為d
的數字數組,其中數字是set(p)
不同組合。 接下來,我想刪除行中的實例比p
實例多。 我可以使用for
循環來完成,這是我的代碼:
import numpy as np
import itertools as it
from collections import Counter
p = [0,0,0,1,1,1,1,2,2,2,2,2,3,3,3,4,4,4,4,4,5,5,5]
assert (len(set(p)) != 1)
cnt = Counter(p)
pos = np.array(list(it.product(set(p), repeat=d)))
ds = []
for i in range(len(pos)):
for j, k in cnt.items():
if len(np.where(pos[i] == j)[0]) > k:
ds.append(i)
pos = np.delete(pos, ds, axis=0)
我正在尋找一種更快的方法。 謝謝!
對於正整數,我們可以使用bincount
。 因此,我們將使用2D
bincount解決方案獲取pos
每行的合並計數,並與p
的合並計數進行比較,並使用該掩碼選擇pos
有效行,如下所示-
# https://stackoverflow.com/a/46256361/ @Divakar
def bincount2D_vectorized(a):
N = a.max()+1
a_offs = a + np.arange(a.shape[0])[:,None]*N
return np.bincount(a_offs.ravel(), minlength=a.shape[0]*N).reshape(-1,N)
pos_out = pos[(bincount2D_vectorized(pos)>np.bincount(p)).any(1)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.