删除范围桶中的数据

2024-03-28 10:56:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我将二维数据存储在元组的排序列表中,如下所示:

data = [(0.1,100), (0.13,300), (0.2,10)...

对于元组列表,每个元组中的第一个值X值只出现一次。换句话说,0.1等只能有一个值

然后我有一个分类的桶列表。bucket定义为包含范围和id的元组,如下所示:

^{pr2}$

范围是相对于X轴的。因此,id 2上面有两个bucket,id1和3分别只有一个bucket。id 2的第一个bucket的范围是0到0.14。请注意,桶可以重叠。在

所以,我需要一个算法,将数据放入桶中,然后将得分相加。对于上述数据,结果如下:

1:0
2:410
3:10

请注意,每个数据片段是如何被与id 2相关联的bucket捕获的,因此它得到了分数100+300+10=410。在

我该如何编写一个算法来实现这一点呢?在


Tags: 数据算法id列表data定义bucket排序
3条回答

这将从测试数据中生成所需的输出:

data = [(0.1,100), (0.13,300), (0.2,10)]
buckets = [((0,0.14), 2), ((0.135,0.19), 1), ((0.19,0.21), 2), ((0.19,0.24), 3)]

totals = dict()

for bucket in buckets:
    bucket_id = bucket[1]
    if bucket_id not in totals:
        totals[bucket_id] = 0
    for data_point in data:
        if data_point[0] >= bucket[0][0] and data_point[0] <= bucket[0][1]:
            totals[bucket_id] += data_point[1]

for key in sorted(totals):
    print("{}: {}".format(key, totals[key]))

将每个bucket定义(label range)转换为一个可调用的(给定数据元组)将增加bucket total。Bucket值存储在一个简单的dict中。如果您想提供一个更简单的api,您可以很容易地将这个概念包装在一个类中。在

def partition(buckets, bucket_definition):
    """Build a callable that increments the appropriate buckets with a value"""

    lower, upper = bucket_definition[0]
    key = bucket_definition[1]

    def _partition(data):
        x, y = data
        # Set a default value for this key
        buckets.setdefault(key, 0)

        if lower <= x <= upper:
            buckets[key] += y

    return _partition


bucket_definitions = [
    ((0, 0.14), 2),
    ((0.135, 0.19), 1),
    ((0.19, 0.21), 2),
    ((0.19, 0.24), 3)
]

data = [(0.1, 100), (0.13, 300), (0.2, 10)]

# Holder for bucket labels and values
buckets = {}

# For each bucket definition (range, label) build a callable
partitioners = [partition(buckets, definition) for definition in bucket_definitions]

# Map each callable to each data tuple provided
for partitioner in partitioners:
    map(partitioner, data)

print(buckets)

请尝试以下代码:

data = [(0.1,100), (0.13,300), (0.2,10)]
buckets = [((0,0.14), 2), ((0.135,0.19), 1), ((0.19,0.21), 2), ((0.19,0.24), 3)]

def foo(tpl): ## determine the buckets a data-tuple is enclosed by list of IDs
    x, s = tpl
    lst = []
    for bucket in buckets:
        rnge, iid = bucket
        if x>rnge[0] and x<rnge[1]: lst.append(iid)
    return lst

data = [[dt, foo(dt)] for dt in data]

scores_dict = {}
for tpl in data:
    score = tpl[0][1]
    for iid in tpl[1]:
        if iid in scores_dict: scores_dict[iid]+=score
        else:                  scores_dict[iid] =score

for key in scores_dict:
    print key,":",scores_dict[key]

此代码段将导致:

^{pr2}$

如果没有打印任何bucket ID,则该bucket中没有X值或总和为零。在

相关问题 更多 >