在 Python Spark 中查看 RDD 内容? [英] View RDD contents in Python Spark?

查看:50
本文介绍了在 Python Spark 中查看 RDD 内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 pyspark 中运行一个简单的应用程序.

f = sc.textFile("README.md")wc = f.flatMap(lambda x: x.split(' ')).map(lambda x: (x, 1)).reduceByKey(add)

我想使用 foreach 操作查看 RDD 内容:

wc.foreach(打印)

这会引发语法错误:

SyntaxError: 无效语法

我错过了什么?

解决方案

此错误是因为 print 不是 Python 2.6 中的函数.

您可以定义执行打印的辅助 UDF,也可以使用 __future__print 视为函数的库:

<预><代码>>>>从操作符导入添加>>>f = sc.textFile("README.md")>>>定义 g(x):... 打印 x...>>>wc.foreach(g)

<预><代码>>>>从 __future__ 导入 print_function>>>wc.foreach(打印)

但是,我认为使用 collect() 将 RDD 内容带回驱动程序会更好,因为 foreach 在工作节点和输出上执行可能不一定出现在您的驱动程序/外壳程序中(它可能会在 local 模式下出现,但在集群上运行时不会出现).

<预><代码>>>>对于 wc.collect() 中的 x:... 打印 x

Running a simple app in pyspark.

f = sc.textFile("README.md")
wc = f.flatMap(lambda x: x.split(' ')).map(lambda x: (x, 1)).reduceByKey(add)

I want to view RDD contents using foreach action:

wc.foreach(print)

This throws a syntax error:

SyntaxError: invalid syntax

What am I missing?

解决方案

This error is because print isn't a function in Python 2.6.

You can either define a helper UDF that performs the print, or use the __future__ library to treat print as a function:

>>> from operator import add
>>> f = sc.textFile("README.md")
>>> def g(x):
...     print x
...
>>> wc.foreach(g)

or

>>> from __future__ import print_function
>>> wc.foreach(print)

However, I think it would be better to use collect() to bring the RDD contents back to the driver, because foreach executes on the worker nodes and the outputs may not necessarily appear in your driver / shell (it probably will in local mode, but not when running on a cluster).

>>> for x in wc.collect():
...     print x

这篇关于在 Python Spark 中查看 RDD 内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆