将 pandas 列转换为DateTime II [英] Convert Pandas Column to DateTime II

查看:68
本文介绍了将 pandas 列转换为DateTime II的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一列DateTime字符串转换为熊猫可理解的Datetime格式.当然,我已经用谷歌搜索并尝试了几种解决方案. 将熊猫"列转换为DateTime

I am trying to convert a column of DateTime Strings into a Pandas-comprehensible Datetime Format. Of course I already googled and tried several solutions. Convert Pandas Column to DateTime

对于我来说,这似乎是最令人鼓舞的,但是两种推荐的方法都不适用于我的数据集. 细节: 数据集名称:co,

This one appeared the most encouraging for me but both recommended ways did not work for my dataset. The details: Dataset name: co,

列:索引列,

格式:2015年7月15日24:00,前后没有空白.

Format: 15.07.2015 24:00 with no more blancs before or after.

我的努力:

co['newdate'] = pd.to_datetime(co.index, format='%d.%m.%Y %H:%M')

在将Index-col转换为名为"Datum"的"normal"列后,我尝试了下一个

The next one I tried after I transformed the Index-col to a "normal" column named "Datum"

co['newdate'] = co['Datum'].apply(lambda x: dt.datetime.strptime(x,'%d.%m.%Y %H:%M'))

错误:时间数据'15 .07.2015 24:00'与格式'%d.%m.%Y%H:%M'不匹配

The error: time data '15.07.2015 24:00' does not match format '%d.%m.%Y %H:%M'

在两个解决方案中均发生此错误.有人有主意吗?

this error occurs in both solutions. Anyone an idea?

推荐答案

您的格式字符串正确,但您的数据不正确,24不是有效的小时部分,因此出现错误:

Your format string is correct but your data is not, 24 is not a valid hour component hence the error:

In [138]:

pd.to_datetime('15.07.2015 24:00', format = '%d.%m.%Y %H:%M')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
C:\WinPython-64bit-3.4.3.5\python-3.4.3.amd64\lib\site-packages\pandas\tseries\tools.py in _convert_listlike(arg, box, format)
    329             try:
--> 330                 values, tz = tslib.datetime_to_datetime64(arg)
    331                 return DatetimeIndex._simple_new(values, None, tz=tz)

pandas\tslib.pyx in pandas.tslib.datetime_to_datetime64 (pandas\tslib.c:23823)()

TypeError: Unrecognized value type: <class 'str'>

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-138-1546fb6950f0> in <module>()
----> 1 pd.to_datetime('15.07.2015 24:00', format = '%d.%m.%Y %H:%M')

C:\WinPython-64bit-3.4.3.5\python-3.4.3.amd64\lib\site-packages\pandas\tseries\tools.py in to_datetime(arg, errors, dayfirst, utc, box, format, exact, coerce, unit, infer_datetime_format)
    343         return _convert_listlike(arg, box, format)
    344 
--> 345     return _convert_listlike(np.array([ arg ]), box, format)[0]
    346 
    347 class DateParseError(ValueError):

C:\WinPython-64bit-3.4.3.5\python-3.4.3.amd64\lib\site-packages\pandas\tseries\tools.py in _convert_listlike(arg, box, format)
    331                 return DatetimeIndex._simple_new(values, None, tz=tz)
    332             except (ValueError, TypeError):
--> 333                 raise e
    334 
    335     if arg is None:

C:\WinPython-64bit-3.4.3.5\python-3.4.3.amd64\lib\site-packages\pandas\tseries\tools.py in _convert_listlike(arg, box, format)
    305                     try:
    306                         result = tslib.array_strptime(
--> 307                             arg, format, exact=exact, coerce=coerce
    308                         )
    309                     except (tslib.OutOfBoundsDatetime):

pandas\tslib.pyx in pandas.tslib.array_strptime (pandas\tslib.c:39900)()

ValueError: time data '15.07.2015 24:00' does not match format '%d.%m.%Y %H:%M' (match)

23:59可以很好地解析

In [139]:
pd.to_datetime('15.07.2015 23:59', format = '%d.%m.%Y %H:%M')

Out[139]:
Timestamp('2015-07-15 23:59:00')

您需要将24替换为0以便对其进行解析:

You need to replace 24 with 0 in order for this to parse:

In [140]:
pd.to_datetime('15.07.2015 00:00', format = '%d.%m.%Y %H:%M')

Out[140]:
Timestamp('2015-07-15 00:00:00')

因此,您可以做的是将向量化的

So what you can do is call the vectorised str.replace to fix these errant hour values:

In [144]:
df = pd.DataFrame({'date':['15.07.2015 24:00']})
print(df)
df['date'] = df['date'].str.replace('24:','00:')
print(df)
pd.to_datetime(df['date'], format = '%d.%m.%Y %H:%M')

               date
0  15.07.2015 24:00
               date
0  15.07.2015 00:00
Out[144]:
0   2015-07-15
Name: date, dtype: datetime64[ns]

因此,您可以这样做:

co.index = co.index.str.replace('24:','00:')

然后像以前一样转换

这篇关于将 pandas 列转换为DateTime II的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆