我有10个箱子:
bins = [0,1,2,3,4,5,6,7,8,9]
我有25个值的列表:
values = [10,0,0,14,14,123,235,0,0,0,0,0,12,12,1235,23,234,15,15,23,136,34,34,37,45]
我想将值按顺序存入bin中,以便将每个值分组到bin:
binnedValues = [[10,0],[0,14,14],[123,235],[0,0,0],[0,0],[12,12,1235],[23,234],[15,15,23],[136,34,34],[37,45]]
正如您所看到的,bin中值的数量并不总是相同的(len(values) != len(bins)
)
另外,我有很多不同大小的不同值列表。因此,对于相同数量的bin,我需要多次执行此操作,但不同长度的值列表。以上是一个例子 - 真正的bin大小为10k,真正的len(值)从~10k到~750k ..
有没有办法一贯地做到这一点?我需要保持值的顺序,但是均匀地拆分值列表,这样就会有一个“公平”和“偶数”的值范围分配给每个二进制位。
我想我可以使用numpy.digitize,但看了之后,我看不出如何生成'binned'列表
答案 0 :(得分:1)
您是否尝试将列表拆分为2到3个元素之间的交替大小的列表?那是可行的。
from itertools import cycle
values = [10,0,0,14,14,123,235,0,0,0,0,0,12,12,1235,23,234,15,15,23,136,34,34,37,45]
splits = cycle([2,3])
bins = []
count = 0
while count < len(values):
splitby = splits.next()
bins.append(values[count:count+splitby])
count += splitby
print bins
修改强>
啊,我看到你要求的......有点儿。更像是:来自itertools导入周期 来自数学进口楼,ceil
values = [10,0,0,14,14,123,235,0,0,0,0,0,12,12,1235,23,234,15,15,23,136,34,34,37,45]
number_bins = 10
bins_lower = int(floor(len(values) / float(number_bins)))
bins_upper = int(ceil(len(values) / float(number_bins)))
splits = cycle([bins_lower, bins_upper])
bins = []
count = 0
while count < len(values):
splitby = splits.next()
bins.append(values[count:count+splitby])
count += splitby
print bins
如果您想要更多种类的bin尺寸,可以向splits
编辑2:
Ashwin的方式,更简洁,更难以理解。
from itertools import cycle, islice
from math import floor, ceil
values = [10,0,0,14,14,123,235,0,0,0,0,0,12,12,1235,23,234,15,15,23,136,34,34,37,45]
number_bins = 10
bins_lower = int(floor(len(values) / float(number_bins)))
bins_upper = int(ceil(len(values) / float(number_bins)))
splits = cycle([bins_lower, bins_upper])
it = iter(values)
bins = [list(islice(it,next(splits))) for _ in range(10)]
print bins