做大数据分析时,经常会使用到空的DataFrame,直接给spark.createDataFrame传递空的Pandas DataFrame会报错:
spark.createDataFrame(data=pd.DataFrame(data=None,columns=['pageid','uid']))
# 报错:
ValueError: can not infer schema from empty dataset
因此总结了几种可以成功创建空的spark DataFrame的方法。
参考:None
df_empty = spark.createDataFrame([], StructType([]))
df_empty.printSchema()
"""
输出:
root
"""
创建schema:
from pyspark.sql.types import StructType,StructField, StringType
schema = StructType([StructField('pageid', StringType(), True),StructField('uid', StringType(), True)])# 查看schema
print(schema.simpleString())
"""
输出:
struct
"""
df_empty1 = spark.createDataFrame([], schema)
df_empty1.printSchema()
"""
输出:
root|-- pageid: string (nullable = true)|-- uid: string (nullable = true)"""
可以通过两种方式创建空的rdd:
rdd1 = spark.sparkContext.emptyRDD()
rdd2 = spark.sparkContext.parallelize([])
df_empty2 = spark.createDataFrame(rdd1,schema)
df_empty2.printSchema()
"""
输出:
root|-- pageid: string (nullable = true)|-- uid: string (nullable = true)
"""
df_empty3 = rdd1.toDF(schema)
df_empty3.printSchema()
"""
输出:
root|-- pageid: string (nullable = true)|-- uid: string (nullable = true)
"""
推荐使用通过“法1”,流程简单:
from pyspark.sql.types import StructType, StructField, StringType
schema = StructType([StructField('pageid', StringType(), True),StructField('uid', StringType(), True)])
df_empty1 = spark.createDataFrame([], schema)
完。
上一篇:学弟:功能测试转测试开发容易吗?
下一篇:描述女人优雅气质的话句