100000,20160214,93374987
100000,20160214,1925301
100000,20160216,1896542
100000,20160216,84167419
100000,20160216,77273616
100000,20160507,1303015
I want to read the csv file which has no column names in first row. How to read it and name the columns with my specified names in the same time ? for now, I just renamed the original columns with my specified names like this:
df = spark.read.csv("user_click_seq.csv",header=False)
df = df.withColumnRenamed("_c0", "member_srl")
df = df.withColumnRenamed("_c1", "click_day")
df = df.withColumnRenamed("_c2", "productid")
Any better way ?
In order to read a CSV file without headers use None value to header param in pandas read_csv() function.
To read CSV file without header, use the header parameter and set it to “None” in the read_csv() method.
You can import the csv file into a dataframe with a predefined schema. The way you define a schema is by using the StructType
and StructField
objects. Assuming your data is all IntegerType
data:
from pyspark.sql.types import StructType, StructField, IntegerType schema = StructType([ StructField("member_srl", IntegerType(), True), StructField("click_day", IntegerType(), True), StructField("productid", IntegerType(), True)]) df = spark.read.csv("user_click_seq.csv",header=False,schema=schema)
should work.
For those who would like to do this in scala and may not want to add types:
val df = spark.read.format("csv")
.option("header","false")
.load("hdfs_filepath")
.toDF("var0","var1","var2","var3")
You can read the data with header=False
and then pass the column names with toDF
as bellow:
data = spark.read.csv('data.csv', header=False)
data = data.toDF('name1', 'name2', 'name3')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With