pandas 将某些值不是日期的列转换为日期时间[重复]

avwztpqn  于 2023-11-15  发布在  其他
关注(0)|答案(1)|浏览(153)

此问题在此处已有答案

AttributeError: Can only use .dt accessor with datetimelike values(8个答案)
15天前关闭
我有一个嵌套框架,其中有一个列grn_date,它由一些日期时间值和一些“-”组成,因为之前我这样填充它:

df['grn_date'].fillna('-', inplace=True)

字符串
之前我对整个列都是这样做的:

# Format the 'date' column to match the rest of the dates
    df['grn_date'] = df['grn_date'].dt.strftime('%Y-%m-%d %H:%M:%S.%f+00:00')

    # Calculate the "Cycle time" by subtracting 'grn_date' from 'date'
    df['allot_date'] = pd.to_datetime(df['allot_date'])  # Ensure 'grn_date' is in datetime format
    df['grn_date'] = pd.to_datetime(df['grn_date'])  # Ensure 'date' is in datetime format

    # Calculate the difference and store it in a new column 'Cycle time'
    df['Cycle time'] = (df['grn_date'] - df['allot_date']).dt.days

    df['grn_date'] = pd.to_datetime(df['grn_date']).dt.strftime('%d-%m-%Y')
    df['allot_date'] = pd.to_datetime(df['allot_date']).dt.strftime('%d-%m-%Y')


但是现在它会给给予错误AttributeError: Can only use .dt accessor with datetimelike values,我必须循环列,并做一个尝试,除了或有任何其他方法来做到这一点?
错误:

Traceback (most recent call last):
  File "/Users/rahulsharma/PycharmProjects/Trakkia-Backend/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/Users/rahulsharma/PycharmProjects/Trakkia-Backend/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/rahulsharma/PycharmProjects/Trakkia-Backend/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/rahulsharma/PycharmProjects/Trakkia-Backend/venv/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Users/rahulsharma/PycharmProjects/Trakkia-Backend/venv/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/rahulsharma/PycharmProjects/Trakkia-Backend/venv/lib/python3.8/site-packages/rest_framework/views.py", line 505, in dispatch
    response = self.handle_exception(exc)
  File "/Users/rahulsharma/PycharmProjects/Trakkia-Backend/venv/lib/python3.8/site-packages/rest_framework/views.py", line 465, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/Users/rahulsharma/PycharmProjects/Trakkia-Backend/venv/lib/python3.8/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception
    raise exc
  File "/Users/rahulsharma/PycharmProjects/Trakkia-Backend/venv/lib/python3.8/site-packages/rest_framework/views.py", line 502, in dispatch
    response = handler(request, *args, **kwargs)
  File "/Users/rahulsharma/PycharmProjects/Trakkia-Backend copy/reports/views.py", line 1421, in get
    df['grn_date'] = df['grn_date'].dt.strftime('%Y-%m-%d %H:%M:%S.%f+00:00')
  File "/Users/rahulsharma/PycharmProjects/Trakkia-Backend/venv/lib/python3.8/site-packages/pandas/core/generic.py", line 5575, in __getattr__
    return object.__getattribute__(self, name)
  File "/Users/rahulsharma/PycharmProjects/Trakkia-Backend/venv/lib/python3.8/site-packages/pandas/core/accessor.py", line 182, in __get__
    accessor_obj = self._accessor(obj)
  File "/Users/rahulsharma/PycharmProjects/Trakkia-Backend/venv/lib/python3.8/site-packages/pandas/core/indexes/accessors.py", line 509, in __new__
    raise AttributeError("Can only use .dt accessor with datetimelike values")
AttributeError: Can only use .dt accessor with datetimelike values
[30/Oct/2023 09:09:16] "GET /rfid-reportsdownload-1/ HTTP/1.1" 500 17740

xmq68pz9

xmq68pz91#

下面是一个最小的例子,有三种情况,一个nan值,一个有效日期和一个连字符。
您可以根据需要将转换函数的errors属性设置为ignorecoerceraise。请参阅文档here。选择coerce以从包含字符串的无效Series生成有效的Date Series。然后,无效数据将被NaT(不是时间)替换,访问器dt将工作。
正如您已经观察到的,包含混合数据的Series(一系列对象)不允许使用.dt表示法

import pandas as pd

df = pd.DataFrame([np.nan, "2023-10-30", "-"], columns=["date-col"])
df["date-col"] = pd.to_datetime(df["date-col"], errors="coerce")

df["date-col"].dt.strftime('%d-%m-%Y')

字符串
输出

0          NaT
1   2023-10-30
2          NaT
Name: date-col, dtype: datetime64[ns]

相关问题