Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/iphone/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在pandas中重新格式化datetime列_Python_Pandas_Datetime_Dataframe - Fatal编程技术网

Python 在pandas中重新格式化datetime列

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

我有一个包含日期时间及其各自值的数据帧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
    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")