ImportError: 无法导入名称 sqlContext

3

我正在使用pyspark将一些csv数据读入到spark Dataframe中。

我尝试按以下方式导入pyspark模块:

from pyspark.sql import sqlContext

为什么会出现以下错误?如何解决?

ImportError: 无法导入名称 sqlContext

我正在使用Python 2.7和Spark 2.0.1

2个回答

3

可能是因为您没有正确设置您的Python路径。在配置Python环境时,我发现以下功能很有用。

def configure_spark(spark_home=None, pyspark_python=None, conf_dir=None):
    """Configures the Python path for importing pyspark

    Sets the SPARK_HOME and PYSPARK_PYTHON environment variables and modifies
    the Python PATH so the pyspark package can be imported.

    Args:
        spark_home (str): Path of SPARK_HOME. Defaults to SPARK_HOME module
            variable.
        pyspark_python (str): Path to Python binary to use in PySpark. Defaults
            to the currently executing Python binary.
        conf_dir (str): Path to configuration directory
    """

    # Set the configuration directory with some basic sanity checks:
    if conf_dir:
        if not os.path.isdir(conf_dir):
            raise OSError("Spark config directory not found: %s" % conf_dir)

        expected_conf = {'spark-env.sh', 'spark-defaults.conf'}
        found_conf = expected_conf - set(os.listdir(conf_dir))
        if found_conf:
            warnings.warn("Some configuration files were not found: %s" % found_conf)

        os.environ['SPARK_CONF_DIR'] = conf_dir

    spark_home = spark_home or SPARK_HOME
    os.environ['SPARK_HOME'] = spark_home

    if not os.path.isdir(spark_home):
        raise OSError("Specified SPARK_HOME is not a valid directory: %s" % spark_home)

    # Add the PySpark directories to the Python path:
    libs = glob(os.path.join(spark_home, 'python', 'lib', '*.zip'))
    if len(libs) < 2:
        raise OSError("Pyspark libraries not found in %s" % spark_home)
    for lib in libs:
        sys.path.insert(1, lib)

    # If PYSPARK_PYTHON isn't specified, use currently running Python binary:
    pyspark_python = pyspark_python or sys.executable
    os.environ['PYSPARK_PYTHON'] = pyspark_python

不知道为什么你没有赞,这个函数很棒,是你自己写的吗? - Tbaki
@Tbaki 是的,我做了,因为我遇到了这个问题很多次。我真的很震惊它不在pyspark代码中。也许他们现在已经添加了它。 - santon
1
据我所知,没有这样的方法,但是每个尝试安装pyspark的人都应该知道这个方法,它让我免受其他方法带来的所有麻烦。非常感谢您的方法,我一定会向周围的人推荐!但是不确定如何给它应有的关注。 :/ - Tbaki

0

您也可以尝试仅使用pyspark,我在我的Jupyter笔记本中遇到了同样的问题,您可以通过以下方式解决

from pyspark import SQLContext

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接