我是潘达斯的新手,我有如下所示的数据
id values
1 2.1
2 0.8
3 1.0
4 3.2我希望将列“值”分隔到不同的回收箱中,如bin =2,并添加一列“计数”,表示在回收箱内的行数,例如:
id values counts
1 2.1 2 (since 2.1 and 3.2 both belong to the bin 2-4)
2 0.8 2
3 1.0 2
4 3.2 2我知道value_counts函数可以计算频率,但我不知道如何将它们添加回原始数据。
任何帮助都是非常感谢的!
发布于 2017-06-12 02:37:12
使用numpy的searchsorted来定义回收箱,使用bincount来计算它们。
这个应该很快。
# This defines the bin edges
# [1, 2, 3] would have created
# different bins
# v
b = np.searchsorted([2], df['values'].values)
df.assign(counts=np.bincount(b)[b])
id values counts
0 1 2.1 2
1 2 0.8 2
2 3 1.0 2
3 4 3.2 2np.searchsorted确定了在第一个数组中,为了保持排序,需要放置第二个数组的每个元素的位置。2.1需要跟踪2,这是1的一个位置。0.8需要位于2之前,这是0的一个位置。1.0需要位于2之前,这是0的一个位置。3.2需要跟踪2,这是1的一个位置。
np.bincount方便地计数积分箱的频率。就像我们刚刚创造的那些。transform的count。发布于 2017-06-12 00:48:05
让我们使用pd.cut和groupby
两个垃圾箱:
df.assign(counts=df.groupby(pd.cut(df['values'], bins=2))['values'].transform('count'))或者,如果您希望您的垃圾箱大小= 2:
df.assign(counts=df.groupby(pd.cut(df['values'], bins=[0,2,4]))['values'].transform('count'))输出:
id values counts
0 1 2.1 2.0
1 2 0.8 2.0
2 3 1.0 2.0
3 4 3.2 2.0https://stackoverflow.com/questions/44489794
复制相似问题