如何在pandas中将列的数据类型从object更改为日期/时间

huangapple go评论64阅读模式
英文:

How to change column dtype from object to Date/Time in pandas

问题

如何将数据和时间列的数据类型从对象数据类型更改为日期和时间数据类型? pd_to_datetime 不起作用。

df['Time'] = pd.to_datetime(df['Time'], format='%H:%M:%S').dt.time
英文:

How to chage the datatypes of Data and Time columns from object datatype to Date and Time datatypes respectively? pd_to_datetime doesnot work.

如何在pandas中将列的数据类型从object更改为日期/时间

df['Time'] = pd.to_datetime(df['Time'], format='%H:%M:%S').dt.time

答案1

得分: 1

一个选项是首先连接日期和时间列:

df["DateTime"] = pd.to_datetime(df["Date"].str.cat(df["Time"], sep=" "))

或者如果在连接后不再需要日期和时间列:

df["DateTime"] = pd.to_datetime(df.pop("Date").str.cat(df.pop("Time"), sep=" "))
英文:

An option is to concat Date and Time columns first:

df["DateTime"] = pd.to_datetime(df["Date"].str.cat(df["Time"], sep=" "))

Or if you no longer need Date and Time columns after the concat:

df["DateTime"] = pd.to_datetime(df.pop("Date").str.cat(df.pop("Time"), sep=" "))

huangapple
  • 本文由 发表于 2023年2月6日 07:55:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75356339.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定