pyspark.sql.DataFrame与pandas.DataFrame之间的相互转换实例
代码如下,步骤流程在代码注释中可见:
# -*- coding: utf-8 -*- import pandas as pd from pyspark.sql import SparkSession from pyspark.sql import SQLContext from pyspark import SparkContext #初始化数据 #初始化pandas DataFrame df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], index=['row1', 'row2'], columns=['c1', 'c2', 'c3']) #打印数据 print df #初始化spark DataFrame sc = SparkContext() if __name__ == "__main__": spark = SparkSession\ .builder\ .appName("testDataFrame")\ .getOrCreate() sentenceData = spark.createDataFrame([ (0.0, "I like Spark"), (1.0, "Pandas is useful"), (2.0, "They are coded by Python ") ], ["label", "sentence"]) #显示数据 sentenceData.select("label").show() #spark.DataFrame 转换成 pandas.DataFrame sqlContest = SQLContext(sc) spark_df = sqlContest.createDataFrame(df) #显示数据 spark_df.select("c1").show() # pandas.DataFrame 转换成 spark.DataFrame pandas_df = sentenceData.toPandas() #打印数据 print pandas_df
程序结果:
相关推荐
81510295 2020-11-17
roamer 2020-10-29
listep 2020-09-11
Tristahong 2020-08-24
三石 2020-08-23
QianYanDai 2020-08-16
Johnson0 2020-07-28
mmmjyjy 2020-07-16
santiago00 2020-07-11
QianYanDai 2020-07-05
QianYanDai 2020-07-05
jiahaohappy 2020-06-21
QianYanDai 2020-06-16
Oeljeklaus 2020-05-29
zhangxiaojiakele 2020-05-25
人家 2020-05-17
jzlixiao 2020-05-15
柠檬班 2020-05-16
jiahaohappy 2020-05-12