【发布时间】:2019-11-30 16:00:37
【问题描述】:
我有一个要写入 HDFS 表的 pandas 数据框。当Srum_Entry_Creation 为StringType() 时,我可以将数据写入表,但我需要它为TimestampType()。这就是我遇到TypeError: TimestampType can not accept object '2019-05-20 12:03:00' in type <class 'str'> 或TypeError: TimestampType can not accept object 1558353780000000000 in type <class 'int'> 的地方。在定义架构之前,我尝试在 python 中将列转换为不同的日期格式,但似乎可以让导入工作。
df
Srum_Entry_ID Connected_Time Machine Srum_Entry_Creation
0 5769.0 0.018218 Computer1 2019-05-20 12:03:00
1 5770.0 0.000359 Computer1 2019-05-20 12:03:00
2 5771.0 0.042674 Computer2 2019-05-20 13:03:00
3 5772.0 0.043229 Computer2 2019-05-20 14:04:00
4 5773.0 0.032222 Computer3 2019-05-20 14:04:00
spark = SparkSession.builder.appName('application').getOrCreate()
schema = StructType([StructField('Srum_Entry_ID', FloatType(), False),
StructField('Connected_Time', FloatType(), True),
StructField('Machine', StringType(), True),
StructField('Srum_Entry_Creation', TimestampType(), True)])
dataframe = spark.createDataFrame(df, schema)
dataframe.write. \
mode("append"). \
option("path", "/user/hive/warehouse/analytics.db/srum_network_connections"). \
saveAsTable("analytics.srum_network_connections")
我试过了:
df['Srum_Entry_Creation'] = df['Srum_Entry_Creation'].astype('datetime64[ns]')
错误:
TypeError: TimestampType can not accept object 1558353780000000000 in type <class 'int'>
和
df['Srum_Entry_Creation'] = pd.to_datetime(df['Srum_Entry_Creation'])
错误:
TypeError: TimestampType can not accept object 1558353780000000000 in type <class 'int'>
和如果我只是将它作为字符串留在熊猫数据框中,我会得到:
错误:TypeError: TimestampType can not accept object '2019-05-20 12:03:00' in type <class 'str'>
【问题讨论】:
-
你试过用日期时间格式替换它吗?
-
我试过 df['Srum_Entry_Creation'] = df['Srum_Entry_Creation'].astype('datetime64[ns]') 和 df['Srum_Entry_Creation'] = pd.to_datetime(df['Srum_Entry_Creation '])
-
还有什么错误?一样吗?
-
我将它们添加到@Steven 的问题中
-
这是一个选项,将时间戳作为字符串从 spark 导出并稍后转换?我知道这有点痛,因为这意味着额外的转换,但如果它有效?!或者是否可以使用
numpy.datetime64代替TimestampType(),因为似乎用作TimestampType的类不能转换为熊猫使用恕我直言的numpy.timestamp64。
标签: python pandas pyspark apache-spark-sql