【发布时间】:2020-07-01 06:24:03
【问题描述】:
假设我在 pyspark 中有这个:
def condi( x ):
if x["age"] <= 2:
return True
else:
return False
def add_count( x ):
global aa
aa += 1
x["count"] += 10000
return x
sc = pyspark.SparkContext( master = 'spark://192.168.56.103:7077',appName = 'test' )
data = [{"age":1,"count":10},{"age":2,"count":20},{"age":3,"count":30}]
data = sc.parallelize( data )
global aa
aa = 0
k = data.map( lambda x : add_count( x ) if condi( x ) else x )
print( k.collect() )
print( aa )
这样的输出:
[{'count': 10010, 'age': 1}, {'count': 10020, 'age': 2}, {'count': 30, 'age': 3}] # data
0 # aa
全局变量aa根本没有修改。
如何使用 map reduce 修改全局变量?
【问题讨论】:
-
什么全局变量
a?我只看到一个全局变量aa。无论如何,您是否尝试检查add_count是否真的被调用,例如通过print在那里发送消息? -
我认为它不会在所有执行者上都可用。考虑使用广播变量-spark.apache.org/docs/latest/api/python/…
-
@Karl Knechtel 是的,实际上 add_count 被调用了!
标签: python apache-spark pyspark mapreduce