我正在从RDD创建一个DataFrame,其中一个值是date。我不知道如何在模式中指定DateType()。
让我来说明一下眼前的问题-
将date加载到DataFrame中的一种方法是首先将其指定为字符串并使用日期()函数将其转换为适当的date。
from pyspark.sql.types import Row, StructType, StructField, StringType, IntegerType, DateType
from pyspark.sql.functions import col, to_date
values=sc.parallelize([(3,'2012-02-02'),(5,'2018-08-08')])
rdd= values.map(lambda t: Row(A=t[0],date=t[1]))
# Importing date as String in Schema
schema = StructType([StructField('A', IntegerType(), True), StructField('date', StringType(), True)])
df = sqlContext.createDataFrame(rdd, schema)
# Finally converting the string into date using to_date() function.
df = df.withColumn('date',to_date(col('date'), 'yyyy-MM-dd'))
df.show()
+---+----------+
| A| date|
+---+----------+
| 3|2012-02-02|
| 5|2018-08-08|
+---+----------+
df.printSchema()
root
|-- A: integer (nullable = true)
|-- date: date (nullable = true)有没有一种方法,我们可以在schema中使用schema,而不必显式地将string转换为date?
就像这样-
values=sc.parallelize([(3,'2012-02-02'),(5,'2018-08-08')])
rdd= values.map(lambda t: Row(A=t[0],date=t[1]))
# Somewhere we would need to specify date format 'yyyy-MM-dd' too, don't know where though.
schema = StructType([StructField('A', DateType(), True), StructField('date', DateType(), True)])更新:@ code 10465355建议的,以下代码工作-
import datetime
schema = StructType([
StructField('A', IntegerType(), True),
StructField('date', DateType(), True)
])
rdd= values.map(lambda t: Row(A=t[0],date=datetime.datetime.strptime(t[1], "%Y-%m-%d")))
df = sqlContext.createDataFrame(rdd, schema)
df.show()
+---+----------+
| A| date|
+---+----------+
| 3|2012-02-02|
| 5|2018-08-08|
+---+----------+
df.printSchema()
root
|-- A: integer (nullable = true)
|-- date: date (nullable = true)发布于 2019-03-07 10:48:42
长话短说,与外部对象的RDD一起使用的模式并不打算以这样的方式使用--声明的类型应该反映数据的实际状态,而不是想要的状态。
换言之,允许:
schema = StructType([
StructField('A', IntegerType(), True),
StructField('date', DateType(), True)
])对应于date字段datetime.date的数据。例如,使用您的RDD[Tuple[int, str]]
import datetime
spark.createDataFrame(
# Since values from the question are just two element tuples
# we can use mapValues to transform the "value"
# but in general case you'll need map
values.mapValues(datetime.date.fromisoformat),
schema
)最接近想要的行为是使用JSON读取器转换数据(RDD[Row]),使用dicts
from pyspark.sql import Row
spark.read.schema(schema).json(rdd.map(Row.asDict))或者更好的显式JSON转储:
import json
spark.read.schema(schema).json(rdd.map(Row.asDict).map(json.dumps))但是,这当然比显式铸造要昂贵得多,在简单的情况下,像您描述的那样,BTW很容易自动化:
from pyspark.sql.functions import col
(spark
.createDataFrame(values, ("a", "date"))
.select([col(f.name).cast(f.dataType) for f in schema]))https://stackoverflow.com/questions/55038612
复制相似问题