gpt4 book ai didi

python - 类型错误 : TimestampType can not accept object and

转载 作者:行者123 更新时间:2023-12-04 13:40:56 27 4
gpt4 key购买 nike

我有一个 Pandas 数据框,我正在写入 HDFS 中的一个表。我可以在 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'>
如果我只是将它保留为 Pandas 数据框中的字符串,我会得到:

错误: TypeError: TimestampType can not accept object '2019-05-20 12:03:00' in type <class 'str'>

最佳答案

总之,我将日期时间转换为纪元时间

df['epoch'] = (df['New_Srum_Entry_Creation'] - dt.datetime(1970,1,1)).dt.total_seconds()
df['epoch'] = df['epoch'].astype('Int64')

然后使用 IntegerType() 作为模式
StructField('epoch', IntegerType(),True)

关于python - 类型错误 : TimestampType can not accept object <class 'str' > and <class 'int' >,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57150045/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com