通过以下方式强制使用架构,可以避免与类型相关的错误:
注意: 创建了一个文本文件 (test.csv),其中包含原始数据(如上所示)和虚构的列名("col1", "col2",...,"col25")。
import pyspark
from pyspark.sql import SparkSession
import pandas as pd
spark = SparkSession.builder.appName('pandasToSparkDF').getOrCreate()
pdDF = pd.read_csv("test.csv")
pandas数据帧的内容:
col1 col2 col3 col4 col5 col6 col7 col8 ...
0 10000001 1 0 1 12:35 OK 10002 1 ...
1 10000001 2 0 1 12:36 OK 10002 1 ...
2 10000002 1 0 4 12:19 PA 10003 1 ...
接下来,创建模式:
from pyspark.sql.types import *
mySchema = StructType([ StructField("col1", LongType(), True)\
,StructField("col2", IntegerType(), True)\
,StructField("col3", IntegerType(), True)\
,StructField("col4", IntegerType(), True)\
,StructField("col5", StringType(), True)\
,StructField("col6", StringType(), True)\
,StructField("col7", IntegerType(), True)\
,StructField("col8", IntegerType(), True)\
,StructField("col9", IntegerType(), True)\
,StructField("col10", IntegerType(), True)\
,StructField("col11", StringType(), True)\
,StructField("col12", StringType(), True)\
,StructField("col13", IntegerType(), True)\
,StructField("col14", IntegerType(), True)\
,StructField("col15", IntegerType(), True)\
,StructField("col16", IntegerType(), True)\
,StructField("col17", IntegerType(), True)\
,StructField("col18", IntegerType(), True)\
,StructField("col19", IntegerType(), True)\
,StructField("col20", IntegerType(), True)\
,StructField("col21", IntegerType(), True)\
,StructField("col22", IntegerType(), True)\
,StructField("col23", IntegerType(), True)\
,StructField("col24", IntegerType(), True)\
,StructField("col25", IntegerType(), True)])
注意: True
(意味着允许为空)
创建Pyspark数据框架:
df = spark.createDataFrame(pdDF,schema=mySchema)
确认Pandas数据帧现在已经转换为PySpark数据帧:
确认Pandas数据帧现在已经转换为PySpark数据帧:
type(df)
输出:
pyspark.sql.dataframe.DataFrame
顺便提一句:
回应Kate在下面的评论-要强制实施一般的(字符串)模式,可以执行以下操作:
df=spark.createDataFrame(pdDF.astype(str))
spark-csv
? - Alberto Bonsantodf = df.replace({np.nan: None})
,在 AWS Glue 的上下文中(Pandas DF -> Spark DF -> Glue Dynamic DF)。问题在于 NA 值会让 Spark 混淆(它们是“float”),而该列的其余部分是整数或字符串。 - Tomasz Gandor