<p>通过按如下方式应用架构可以避免与类型相关的错误:</p>
<p><strong>注意</strong>:创建了一个文本文件(<em>test.csv</em>),其中包含原始数据(如上所述),并插入了假设的列名(“col1”、“col2”…、“col25”)。</p>
<pre><code>import pyspark
from pyspark.sql import SparkSession
import pandas as pd
spark = SparkSession.builder.appName('pandasToSparkDF').getOrCreate()
pdDF = pd.read_csv("test.csv")
</code></pre>
<p>熊猫数据框的内容:</p>
<pre><code>pdDF
col1 col2 col3 col4 col5 col6 col7 col8 col9 col10 ... col16 col17 col18 col19 col20 col21 col22 col23 col24 col25
0 10000001 1 0 1 12:35 OK 10002 1 0 9 ... 3 9 0 0 1 1 0 0 4 543
1 10000001 2 0 1 12:36 OK 10002 1 0 9 ... 3 9 2 1 1 3 1 3 2 611
2 10000002 1 0 4 12:19 PA 10003 1 1 7 ... 2 15 2 0 2 3 1 2 2 691
</code></pre>
<p>接下来,创建架构:</p>
<pre><code>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)])
</code></pre>
<p><strong>注意</strong>:<code>True</code>(表示允许为空)</p>
<p>创建pyspark数据帧:</p>
<pre><code>df = spark.createDataFrame(pdDF,schema=mySchema)
</code></pre>
<p>确认pandas数据帧现在是pyspark数据帧:</p>
<pre><code>type(df)
</code></pre>
<p>输出:</p>
<pre><code>pyspark.sql.dataframe.DataFrame
</code></pre>
<p><strong>旁边</strong>:</p>
<p>要处理凯特在下面的评论-要强制使用通用(字符串)架构,可以执行以下操作:</p>
<pre><code>df=spark.createDataFrame(pdDF.astype(str))
</code></pre>