2016-07-26 76 views
1

比方說,我創建了一些數據,然後創建不同大小的垃圾箱:分箱,然後用最小數量的觀察結合箱子?

from __future__ import division 
x = np.random.rand(1,20) 
new, = np.digitize(x,np.arange(1,x.shape[1]+1)/100) 
new_series = pd.Series(new) 
print(new_series.value_counts()) 

顯示:

20 17 
16 1 
4 1 
2 1 
dtype: int64 

我基本上要變換的基礎數據,如果我至少設置一個最低門檻2每個塊,以使得new_series.value_counts()是這樣的:

20 17 
16 3 
dtype: int64 
+0

IIUC你可以使用'groupby'和'filter':'df.groupby('some_col')。filter(lambda x:len(x) EdChum

+0

你能否提供示例輸出並闡明你的輸入?假設'x'是你的數據,'new'是你的bin,它們不重疊,'x'是小數數組,'new'是整數數組。 「新」是垃圾箱的大小嗎?開始界限在哪裏? – tmthydvnprt

+0

你能提供一個含有數據和垃圾箱的簡單小數據集,然後手創建所需的輸出嗎?感謝將是描述你想要做什麼的最清晰的方式。 – tmthydvnprt

回答

1

編輯:

x = np.random.rand(1,100) 
bins = np.arange(1,x.shape[1]+1)/100 

new = np.digitize(x,bins) 
n = new.copy()[0] # this will hold the the result 

threshold = 2 

for i in np.unique(n): 
    if sum(n == i) <= threshold: 
     n[n == i] += 1 

n.clip(0, bins.size) # avoid adding beyond the last bin 
n = n.reshape(1,-1) 

這可以移動向上計數多次,直到bin被充滿。

代替使用np.digitize,使用np.histogram代替它可能會更簡單,因爲它會直接爲您提供計數,因此我們不需要sum自己。

+0

由於某些原因,如果我在上面的例子中使用它,然後通過將其更改爲pd.Series()來查看value_counts(),它不會更改任何內容。也許我做錯了什麼。 – BobbyJohnsonOG

+0

沒有特別的理由(1,100) - 數據是從熊貓數據框的一列中提取的 – BobbyJohnsonOG

+0

我會在一分鐘內嘗試更新的答案,謝謝你的幫助。 – BobbyJohnsonOG