3

I am trying to read a text file in spark 2.3 using python,but I get this error. This is the format textFile is in:

name marks
amar 100
babul 70
ram 98
krish 45

Code:

df=spark.read.option("header","true")\
    .option("delimiter"," ")\
    .option("inferSchema","true")\
    .schema(
        StructType(
            [
                StructField("Name",StringType()),
                StructField("marks",IntegerType())
            ]
        )
    )\
    .text("file:/home/maria_dev/prac.txt") 

Error:

java.lang.AssertionError: assertion failed: Text data source only
produces a single data column named "value"

While I am trying to read a textFile into an RDD, its being collected as a single column.

Should the data file should be changed or shoud I change my code?

4

1 回答 1

5

Instead of .text(produces only single value column) use .csv to load file into DF.

>>> df=spark.read.option("header","true")\
    .option("delimiter"," ")\
    .option("inferSchema","true")\
    .schema(
        StructType(
            [
                StructField("Name",StringType()),
                StructField("marks",IntegerType())
            ]
        )
    )\
    .csv('file:///home/maria_dev/prac.txt') 

>>> from pyspark.sql.types import *
>>> df
DataFrame[Name: string, marks: int]
>>> df.show(10,False)
+-----+-----+
|Name |marks|
+-----+-----+
|amar |100  |
|babul|70   |
|ram  |98   |
|krish|45   |
+-----+-----+
于 2018-09-18T02:06:54.743 回答