如何修改 Spark 数据框中的 numpy 数组?
Posted
技术标签:
【中文标题】如何修改 Spark 数据框中的 numpy 数组?【英文标题】:How to modify numpy arrays in Spark dataframe? 【发布时间】:2016-06-22 20:24:19 【问题描述】:问题: 在 lambda 或 dataframe 转换中不允许分配,这意味着我们通常必须为使用 Spark 在 Dataframes 中完成的每个数据操作创建一个新结构。
示例(Python): 我以前通过简单地就地创建修改后的数据而不在列表和字典中赋值来解决这个问题,但是事实证明 numpy 算法非常麻烦。我已经对将所有这些数据放入列表进行了一些模拟,由于数组非常大,它会显着减慢。 (例如,这些数组每个大约有 3K 元素长,包含在每 db 行 30 个数组的列表中,数百万行)
a = np.zeros(5)
# Actual operation
a[1:3] += 7
print "".format(a)
>> [ 0. 7. 7. 0. 0.]
# Spark compatability - Create modified array in memory to avoid assignment
# Not sure if this is best "solution" performance-wise
c = np.concatenate([a[:1], a[1:3] + 7, a[3:]])
print "\n".format(c)
>> [ 0. 7. 7. 0. 0.]
示例(pyspark): 所以现在你可以看到我期待的输出,这里是 Spark 版本。
t = sc.parallelize(a)
t2 = t.map(lambda ar: np.concatenate([ar[:1], ar[1:3] + 7, ar[3:]]))
t2.take(1)
错误: 我认为这会起作用,但是我明白了。我认为问题是这个“ar [1:3] + 7”但是在没有它的情况下运行它之后,它仍然给出了同样的错误。也许我缺少一些东西。
也许 np.concatenate() 做了某种分配,导致 这。如果是这种情况,有什么办法可以解决它?
---------------------------------------------------------------------------
Py4JJavaError Traceback (most recent call last)
<ipython-input-46-4a4c467a0b3d> in <module>()
12 t = sc.parallelize(a)
13 t2 = t.map(lambda ar: np.concatenate([ar[:1], ar[1:3] + 7, ar[3:]]))
---> 14 t2.take(1)
/databricks/spark/python/pyspark/rdd.py in take(self, num)
1297
1298 p = range(partsScanned, min(partsScanned + numPartsToTry, totalParts))
-> 1299 res = self.context.runJob(self, takeUpToNumLeft, p)
1300
1301 items += res
/databricks/spark/python/pyspark/context.py in runJob(self, rdd, partitionFunc, partitions, allowLocal)
914 # SparkContext#runJob.
915 mappedRDD = rdd.mapPartitions(partitionFunc)
--> 916 port = self._jvm.PythonRDD.runJob(self._jsc.sc(), mappedRDD._jrdd, partitions)
917 return list(_load_from_socket(port, mappedRDD._jrdd_deserializer))
918
/databricks/spark/python/lib/py4j-0.8.2.1-src.zip/py4j/java_gateway.py in __call__(self, *args)
536 answer = self.gateway_client.send_command(command)
537 return_value = get_return_value(answer, self.gateway_client,
--> 538 self.target_id, self.name)
539
540 for temp_arg in temp_args:
/databricks/spark/python/pyspark/sql/utils.py in deco(*a, **kw)
34 def deco(*a, **kw):
35 try:
---> 36 return f(*a, **kw)
37 except py4j.protocol.Py4JJavaError as e:
38 s = e.java_exception.toString()
/databricks/spark/python/lib/py4j-0.8.2.1-src.zip/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name)
298 raise Py4JJavaError(
299 'An error occurred while calling 012.\n'.
--> 300 format(target_id, '.', name), value)
301 else:
302 raise Py4JError(
Py4JJavaError: An error occurred while calling z:org.apache.spark.api.python.PythonRDD.runJob.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 25.0 failed 1 times, most recent failure: Lost task 0.0 in stage 25.0 (TID 30, localhost): org.apache.spark.api.python.PythonException: Traceback (most recent call last):
File "/databricks/spark/python/pyspark/worker.py", line 111, in main
process()
File "/databricks/spark/python/pyspark/worker.py", line 106, in process
serializer.dump_stream(func(split_index, iterator), outfile)
File "/databricks/spark/python/pyspark/serializers.py", line 263, in dump_stream
vs = list(itertools.islice(iterator, batch))
File "/databricks/spark/python/pyspark/rdd.py", line 1295, in takeUpToNumLeft
yield next(iterator)
File "<ipython-input-46-4a4c467a0b3d>", line 13, in <lambda>
IndexError: invalid index to scalar variable.
at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRDD.scala:166)
at org.apache.spark.api.python.PythonRunner$$anon$1.<init>(PythonRDD.scala:207)
at org.apache.spark.api.python.PythonRunner.compute(PythonRDD.scala:125)
at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:70)
at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:300)
at org.apache.spark.rdd.RDD.iterator(RDD.scala:264)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66)
at org.apache.spark.scheduler.Task.run(Task.scala:88)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:214)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Driver stacktrace:
at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1283)
at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1271)
at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1270)
at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:47)
at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1270)
at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:697)
at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:697)
at scala.Option.foreach(Option.scala:236)
at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:697)
at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:1496)
at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1458)
at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1447)
at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48)
at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:567)
at org.apache.spark.SparkContext.runJob(SparkContext.scala:1827)
at org.apache.spark.SparkContext.runJob(SparkContext.scala:1840)
at org.apache.spark.SparkContext.runJob(SparkContext.scala:1853)
at org.apache.spark.api.python.PythonRDD$.runJob(PythonRDD.scala:393)
at org.apache.spark.api.python.PythonRDD.runJob(PythonRDD.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:231)
at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:379)
at py4j.Gateway.invoke(Gateway.java:259)
at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:133)
at py4j.commands.CallCommand.execute(CallCommand.java:79)
at py4j.GatewayConnection.run(GatewayConnection.java:207)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.spark.api.python.PythonException: Traceback (most recent call last):
File "/databricks/spark/python/pyspark/worker.py", line 111, in main
process()
File "/databricks/spark/python/pyspark/worker.py", line 106, in process
serializer.dump_stream(func(split_index, iterator), outfile)
File "/databricks/spark/python/pyspark/serializers.py", line 263, in dump_stream
vs = list(itertools.islice(iterator, batch))
File "/databricks/spark/python/pyspark/rdd.py", line 1295, in takeUpToNumLeft
yield next(iterator)
File "<ipython-input-46-4a4c467a0b3d>", line 13, in <lambda>
IndexError: invalid index to scalar variable.
at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRDD.scala:166)
at org.apache.spark.api.python.PythonRunner$$anon$1.<init>(PythonRDD.scala:207)
at org.apache.spark.api.python.PythonRunner.compute(PythonRDD.scala:125)
at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:70)
at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:300)
at org.apache.spark.rdd.RDD.iterator(RDD.scala:264)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66)
at org.apache.spark.scheduler.Task.run(Task.scala:88)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:214)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
... 1 more
【问题讨论】:
【参考方案1】:问题的根源远不止于此。当您执行sc.parallelize(a)
时,输入数组将转换为列表,并且此列表的元素成为RDD
的元素。因此,当您执行map
时,它会将函数分别应用于输入的每个元素。所以它相当于这样的东西:
f = lambda ar: np.concatenate([ar[:1], ar[1:3] + 7, ar[3:]])
[f(x) for x in list(a)]
## IndexError
## ...
## IndexError: invalid index to scalar variable.
因此您会看到错误。你想要的很可能是这样的:
sc.parallelize([a]).map(f).take(1)
## [array([ 0., 14., 14., 0., 0.])]
还有两点值得注意:
使用高阶函数时,Spark 不需要 lambda 表达式。唯一的要求是你传递的函数不应该修改它的参数并且最好是纯的。在实践中,如果您知道内部发生了什么,那么您可以在 PySpark(一般不是 Spark)中修改数据,但这不是您在实践中应该做的事情。因此,要回答标题中的问题,请不要尝试。 Lambda 表达式没有任何防止副作用的魔法保护。您根本不能直接在其主体内使用语句。【讨论】:
以上是关于如何修改 Spark 数据框中的 numpy 数组?的主要内容,如果未能解决你的问题,请参考以下文章
使用 pyspark 将 Spark 数据框中的列转换为数组 [重复]
如何将 numpy 数组存储在 Pandas 数据框的列中?
如何将 numpy 数组存储在 Pandas 数据框的列中?