如何向 PySpark DataFrame 添加标头?

Ann*_*ana 3 apache-spark apache-spark-sql pyspark

我创建了一个没有标题的 PySpark RDD(从 XML 转换为 CSV)。我需要将其转换为带有标头的 DataFrame,以便对其执行一些 SparkSQL 查询。我似乎找不到添加标题的简单方法。大多数示例都从已有标题的数据集开始。

    df = spark.read.csv('some.csv', header=True, schema=schema)
Run Code Online (Sandbox Code Playgroud)

但是,我需要附加标题。

    headers = ['a', 'b', 'c', 'd']
Run Code Online (Sandbox Code Playgroud)

这似乎是一个微不足道的问题,我不确定为什么我找不到有效的解决方案。谢谢。

the*_*hon 6

像这样...您需要指定架构,并且.option("header", "false")如果您的 csv 不包含标题行

spark.version
'2.3.2'

! cat sample.csv

1, 2.0,"hello"
3, 4.0, "there"
5, 6.0, "how are you?"

PATH = "sample.csv"

from pyspark.sql.functions import *
from pyspark.sql.types import *

schema = StructType([\
    StructField("col1", IntegerType(), True),\
    StructField("col2", FloatType(), True),\
    StructField("col3", StringType(), True)])

csvFile = spark.read.format("csv")\
.option("header", "false")\
.schema(schema)\
.load(PATH)

csvFile.show()

+----+----+---------------+
|col1|col2|           col3|
+----+----+---------------+
|   1| 2.0|          hello|
|   3| 4.0|        "there"|
|   5| 6.0| "how are you?"|
+----+----+---------------+

# if you have rdd and want to convert straight to df
rdd = sc.textFile(PATH)

# just showing rows
for i in rdd.collect(): print(i)
1, 2.0,"hello"
3, 4.0, "there"
5, 6.0, "how are you?"

# use Row to construct a schema from rdd
from pyspark.sql import Row

csvDF = rdd\
    .map(lambda x: Row(col1 = int(x.split(",")[0]),\
                       col2 = float(x.split(",")[1]),\
                       col3 = str(x.split(",")[2]))).toDF()

csvDF.show()
+----+----+---------------+
|col1|col2|           col3|
+----+----+---------------+
|   1| 2.0|        "hello"|
|   3| 4.0|        "there"|
|   5| 6.0| "how are you?"|
+----+----+---------------+

csvDF.printSchema()
root
 |-- col1: long (nullable = true)
 |-- col2: double (nullable = true)
 |-- col3: string (nullable = true)

Run Code Online (Sandbox Code Playgroud)


小智 5

rdd.toDF(模式=['a', 'b', 'c', 'd']