[英]Running a function in the last RDD in spark
我有一個 python 程序來分析數據並想用 Spark 運行它。 我在工人之間分配數據並對其進行一些轉換。 但最后我需要將結果收集到主節點並在其上運行另一個 function。
在驅動程序上,我有以下代碼:
sc = SparkContext(conf=spark_conf)
sc.parallelize(group_list, 4) \
.map(function1, preservesPartitioning=True) \
.map(function2, preservesPartitioning=True) \
.map(function3, preservesPartitioning=True) \
.map(function4, preservesPartitioning=True) \
.map(function5, preservesPartitioning=True) \
.map(function6, preservesPartitioning=True) \
.map(function7, preservesPartitioning=True) \
.map(function8, preservesPartitioning=True) \
.map(function9, preservesPartitioning=True)
function9生成的最后一個 RDD 是一個包含多行和唯一鍵的表。 當主節點從worker收集所有最后一個RDD時,它們在主節點中有重復的行。 我必須按最后一個表分組並對某些列進行一些聚合,所以我有一個最終的 function ,它采用最后一個表並對其進行分組和聚合。 但是我不知道如何通過最終的function上的最后一個RDD。
例如在worker1上,我有這個數據:
key count average
B 3 0.2
x 2 0.1
y 5 1.2
在worker2上,我有這些數據:
key count average
B 2 0.1
c 1 0.01
x 3 0.34
當主節點從worker接收到所有數據時,它有:
key count average
B 3 0.2
x 2 0.1
y 5 1.2
B 2 0.1
c 1 0.01
x 3 0.34
您會看到數據有兩個B和兩個x鍵。 我必須在主節點中使用另一個 function 來按關鍵列分組並計算平均列的新平均值。 我使用了reduce並給出了我的最終 function,但它給了我錯誤,因為它需要兩個 arguments。 請您指導我可以使用什么火花動作在最后一個 RDD 上運行我的 function?
任何指導將不勝感激。
我建議你傳遞給 DataFrame 格式(使用起來更簡單),然后應用這個:
df.groupBy('key').agg(f.sum('count'), f.avg('average'))
如果你想保持 rdd 格式,你應該做這樣的事情,但應用平均值而不是列表。
從您寫的內容來看,這應該可行:
sqlContext = sql.SQLContext(sc)
from pyspark.sql import SQLContext
(sqlContext.createDataFrame(
[['B',3,0.2],
['x',2,0.1],
['y',5,1.2],
['B',2,0.1],
['c',1,0.01],
['x',3,0.34]], ['key', 'count', 'average'])
.groupBy('key')
.agg(f.sum('count').alias('count'), f.avg('average').alias('avg'))
.show()
)
您可以(並且可能應該)傳遞初始 rdd sc.parallelize(group_list, 4)
,在這種情況下f.sum()
應該是f.count()
。 希望這可以幫助
例如,我有一個 pandas Dataframe 像這樣:
'a' 'b'
1 3
1 4
2 5
我寫了一個 function 在 groupby 中使用:
def process_json(x):
print(x)
temp = 0
for item in x.items():
temp += item[1]
print('-------', temp)
所以,
a.groupby(['a'])['b'].agg(process_json)
Output 是:
0 3
1 4
Name: b, dtype: int64
------- 7
2 5
Name: b, dtype: int64
------- 5
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.