2016-07-26 77 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