![](/img/trans.png)
[英]PySpark: TypeError: StructType can not accept object in type <type 'unicode'> or <type 'str'>
[英]TypeError: StructType can not accept object '1/1/2021 1:00:00 AM' in type
我想在 PySpark 中創建一個簡單的 dataframe。此數據幀應包含一個時間戳字符串“1/1/2021 1:00:00 AM”,稍后我想將其從字符串轉換為時間戳。
這是我當前的代碼。 當我運行它時,出現錯誤“TypeError: StructType cannot accept object '1/1/2021 1:00:00 AM' in type”。 我怎樣才能以最終可以成功執行to_timestamp
的方式修復它?
from pyspark.sql.functions import to_timestamp
from pyspark.sql.types import StringType, StructType, StructField
schema = StructType([
StructField("timestamp_str", StringType(), True)
])
data = [("1/1/2021 1:00:00 AM")]
df = spark.createDataFrame(data, schema=schema)
df = df.withColumn("timestamp", to_timestamp("timestamp_str", "MM/dd/yyyy hh:mm:ss a"))
更新:
將data = [("1/1/2021 1:00:00 AM")]
更改為data = [("1/1/2021 1:00:00 AM",)]
我收到另一個錯誤。 當我運行df.show()
時出現:
org.apache.spark.SparkException:作業因階段失敗而中止:階段 2.0 中的任務 2 失敗 4 次,最近的失敗:階段 2.0 中的任務 2.3 丟失 (TID 10) (10.233.49.69 執行程序 0):org.apache。 spark.SparkUpgradeException: [INCONSISTENT_BEHAVIOR_CROSS_VERSION.PARSE_DATETIME_BY_NEW_PARSER] 由於升級到 Spark >= 3.0,您可能會得到不同的結果:
引入一個新的列 id 並在創建 df 后將其刪除。 當您創建單列 df 時,Spark 會拋出錯誤。
from pyspark.sql.functions import to_timestamp
from pyspark.sql.types import StringType, StructType, StructField
spark.sql("set spark.sql.legacy.timeParserPolicy=LEGACY")
schema = StructType([ StructField("id", StringType(), True),StructField("timestamp_str", StringType(), True)])
data = [('1',"1/1/2021 1:00:00 AM")]
df = spark.createDataFrame(data, schema=schema).drop('id')
df= df.withColumn("timestamp", to_timestamp("timestamp_str", "MM/dd/yyyy hh:mm:ss a"))
df.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.