Pandas - 没有空值但 pd.to_datetime 给出“重新索引仅对唯一值的索引值有效”? 示例数据错误我尝试了什么

问题描述

示例数据

+---------+------------------------+
|         |          date          |
+---------+------------------------+
|       0 | 2020-12-31 00:00:00    |
|       1 |    2020-12-31 00:00:00 |
|       2 |    2020-12-31 00:00:00 |
|       3 |    2020-06-11 00:00:00 |
|       4 |   2020-03-10 00:00:00  |
|  172588 | 2020-03-05 00:00:00    |
|  172589 | 2020-03-05 00:00:00    |
|  172590 | 2020-01-27 00:00:00    |
|  172591 | 2020-01-20 00:00:00    |
| 172592  | 2020-01-07 00:00:00    |
+---------+------------------------+

错误

df["date"] = pd.to_datetime(df["date"],errors="coerce").dt.strftime("%Y-%m-%d")

产生以下错误

~\miniconda3\lib\site-packages\pandas\core\tools\datetimes.py in to_datetime(arg,errors,dayfirst,yearfirst,utc,format,exact,unit,infer_datetime_format,origin,cache)
    799         cache_array = _maybe_cache(arg,cache,convert_listlike)
    800         if not cache_array.empty:
--> 801             result = arg.map(cache_array)
    802         else:
    803             values = convert_listlike(arg._values,format)

~\miniconda3\lib\site-packages\pandas\core\series.py in map(self,arg,na_action)
   3968         dtype: object
   3969         """
-> 3970         new_values = super()._map_values(arg,na_action=na_action)
   3971         return self._constructor(new_values,index=self.index).__finalize__(
   3972             self,method="map"

~\miniconda3\lib\site-packages\pandas\core\base.py in _map_values(self,mapper,na_action)
   1129             values = self._values
   1130 
-> 1131             indexer = mapper.index.get_indexer(values)
   1132             new_values = algorithms.take_1d(mapper._values,indexer)
   1133 

~\miniconda3\lib\site-packages\pandas\core\indexes\base.py in get_indexer(self,target,method,limit,tolerance)
   2984 
   2985         if not self.is_unique:
-> 2986             raise InvalidindexError(
   2987                 "Reindexing only valid with uniquely valued Index objects"
   2988             )

InvalidindexError: Reindexing only valid with uniquely valued Index objects

我尝试了什么

pd.to_datetime producing "Reindexing only valid with uniquely valued Index objects"

Resolving Reindexing only valid with uniquely valued Index objects

为什么不一样

  1. 日期列中肯定有重复项,但它不是索引
  2. 如第一个链接所建议的那样,此列中没有 null/na 值。因此,使所有 NaT/Null/Na 值唯一并不能解决问题

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)