python - 齐柏林飞艇 : Scala Dataframe to python

标签 python apache-spark pyspark apache-zeppelin

如果我有一个带有 DataFrame 的 Scala 段落,我可以与 python 共享和使用它吗? (据我了解,pyspark 使用 py4j )

我试过这个:

Scala 段落:

x.printSchema
z.put("xtable", x )

Python 段落:

%pyspark

import numpy as np
import pandas as pd

import matplotlib.pyplot as plt
import seaborn as sns

the_data = z.get("xtable")

print the_data

sns.set()
g = sns.PairGrid(data=the_data,
                 x_vars=dependent_var,
                 y_vars=sensor_measure_columns_names +  operational_settings_columns_names,
                 hue="UnitNumber", size=3, aspect=2.5)
g = g.map(plt.plot, alpha=0.5)
g = g.set(xlim=(300,0))
g = g.add_legend()

错误:

Traceback (most recent call last):
  File "/tmp/zeppelin_pyspark.py", line 222, in <module>
    eval(compiledCode)
  File "<string>", line 15, in <module>
  File "/usr/local/lib/python2.7/dist-packages/seaborn/axisgrid.py", line 1223, in __init__
    hue_names = utils.categorical_order(data[hue], hue_order)
TypeError: 'JavaObject' object has no attribute '__getitem__'

解决方案:

%pyspark

import numpy as np
import pandas as pd

import matplotlib.pyplot as plt
import seaborn as sns

import StringIO
def show(p):
    img = StringIO.StringIO()
    p.savefig(img, format='svg')
    img.seek(0)
    print "%html <div style='width:600px'>" + img.buf + "</div>"

df = sqlContext.table("fd").select()
df.printSchema
pdf = df.toPandas()

g = sns.pairplot(data=pdf,
                 x_vars=["setting1","setting2"],
                 y_vars=["s4", "s3", 
                         "s9", "s8", 
                         "s13", "s6"],
                 hue="id", aspect=2)
show(g)   

cluster visualisation

最佳答案

您可以在 Scala 中将 DataFrame 注册为临时表:

// registerTempTable in Spark 1.x
df.createTempView("df")

并使用 SQLContext.table 在 Python 中读取它:

df = sqlContext.table("df")

如果您真的想使用put/get,您需要从头开始构建 Python DataFrame:

z.put("df", df: org.apache.spark.sql.DataFrame)
from pyspark.sql import DataFrame

df = DataFrame(z.get("df"), sqlContext)

要使用 matplotlib 绘图,您需要使用 collecttoPandasDataFrame 转换为本地 Python 对象>:

pdf = df.toPandas()

请注意,它将获取数据到驱动程序。

另见 moving Spark DataFrame from Python to Scala whithn Zeppelin

关于python - 齐柏林飞艇 : Scala Dataframe to python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35719142/

相关文章:

python - 值包含空格的属性的 Css 选择器

python - 如何配置带有 Python 扩展的 Visual Studio Code 以不提示无法导入模块?

python - Docker - 从容器内部运行容器

apache-spark - 在pyspark中读取json文件

apache-spark - 在pyspark中,spark.read()和spark.readstream()有什么区别?

python - 在 xlim 范围之外可访问的 matplotlib 数据

apache-spark - 在 PySpark 中,如何从转换内部登录到 log4j

apache-spark - 如何将列表转换为JavaRDD

sql - 使用复杂类型查询 Spark SQL DataFrame

pyspark randomForest 特征重要性 : how to get column names from the column numbers