Spark&python2.7复杂数据结构GroupByKey

2024-09-27 23:28:30 发布

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

我有一个rdd,看起来像这样:

totalsrdd = [((2, 16),[[1,2,3,...,36],[2,2,3,...,36]]),((2,17),[[1,2,3,...,36]]),...]

键是天(2,16)等,它们分别对应一个或多个36个数字的列表。对于每个日期,我需要一个列表,其中列表中的第I个条目是每个列表中第I个条目的平均值。你知道吗

例如,对于(2,16),第一个条目的平均值为(1+2)/(36+36)或.04166,因为该日期有两个列表。你知道吗

newRdd = [((2,16),[[.04166,.055555,.083333,...,1]]),(2,17),[[.027777,.055555,.083333,...,1]]),...]

因为(2,17)只有一个列表,所以列表中的每个条目都除以36。你知道吗

这是我目前掌握的密码。数据远不止两个日期。你知道吗

def get_partition(x):
    j = [(x[1][i]).total_seconds() for i in range(len(x[1]))]
    return (x[0],j)
newTimeDeltaRdd2 = newtimeDeltaRdd.map(lambda x : ((x[1].month,x[1].day), x[0]))
totals = newTimeDeltaRdd2.map(lambda x: (get_partition(x)))
totalsrdd = totals.groupByKey().map(lambda x : (x[0], list(x[1])))

谢谢!你知道吗


Tags: lambda目的密码map列表get条目数字
2条回答

快速和肮脏的解决方案,将给你描述的行为。你知道吗

我还是会考虑用字典

import numpy as np
for entry in totalsrdd:
    sum = np.zeros(36)
    for ls in entry[1]:
        sum = np.add(sum, ls)
    sum = np.divide(sum, len(entry[1]) * 36)
    entry[1] = sum

下面是获得newrdd的可能解决方案:

totalsrdd = [((2, 16),[[1,2,3,...,36],[2,2,3,...,36]]),((2,17),[[1,2,3,...,36]]),...]

newrdd = []
for key, _list in totalsrdd:
    averages = []
    for i in range(36):
        averages.append(sum([_l[i] for _l in _list]) / 36 * len(_list))
    newrdd.append((key, averages)) 

相关问题 更多 >

    热门问题