Python 在pandas中重新格式化datetime列
我有一个包含日期时间及其各自值的数据帧df。现在我想对数据帧中的每个datetime进行一些格式更改,但注意到普通for循环实际上并没有更改数据帧中的任何内容 这就是我所尝试的,也展示了我所尝试的:Python 在pandas中重新格式化datetime列,python,pandas,datetime,dataframe,Python,Pandas,Datetime,Dataframe,我有一个包含日期时间及其各自值的数据帧df。现在我想对数据帧中的每个datetime进行一些格式更改,但注意到普通for循环实际上并没有更改数据帧中的任何内容 这就是我所尝试的,也展示了我所尝试的: #original format of the datetimes: sunnuntai 1.1.2017 00:00 for i in df["Datetime"]: #removes the string containing the weekday from the beginning
#original format of the datetimes: sunnuntai 1.1.2017 00:00
for i in df["Datetime"]:
#removes the string containing the weekday from the beginning
i = re.sub("^[^ ]* ","", i)
#converts 1.1.2017 00:00 into 2017-01-01 00:00
i = datetime.datetime.strptime(i, "%d.%m.%Y %H:%M").strftime("%Y-%m-%d %H:%M")
我应该如何永久地进行这些格式更改?谢谢。放弃循环,目标是矢量化。我打破了台阶-
str.split
删除前导文本pd.to_datetime
与dayfirst=True
进行日期时间转换,以及dt.strftime
将结果转换为您的格式sunnutai
也是数据的一部分吗?是的,但我想删除它(这是工作日),只保留日期和时间,如2017-01-01 00:00。原来的我是“Sunnutai 1.1.2017 00:00”,“Sunnutai 1.1.2017 01:00”等等。谢谢你,成功了!使用Pandas似乎与使用“普通”python列表和字典有很大不同,我认为使用for循环是一种很好的方法。
df['Datetime'] = pd.to_datetime(
df['Datetime'].str.split(n=1).str[1], dayfirst=True
).dt.strftime("%Y-%m-%d %H:%M")