从纠正一个误解开始
我注意到你的检查程序存在以下错误:
调用df.index.duplicated().any()
只检查索引是否有重复。
为了调查这个问题,我使用了你的数据创建了一个输入文件(只包含10行数据):
colx
2017-01-06 14:37:16
2017-01-27 00:00:00
2017-01-18 00:00:00
2017-01-26 00:00:00
None
2019-10-22 11:20:03
None
2019-07-11 00:00:00
None
2019-07-15 00:00:00
我调用了read_csv函数,然后调用了df.duplicated().any()
,结果为True,因此在colx列中存在重复项。
运行df.duplicated()
,你会看到对于索引为6和8(第二个和第三个None字符串实例)的行,打印出了True。
另一个检查:运行df.info()
,你将得到:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 10 entries, 0 to 9
Data columns (total 1 columns):
colx 10 non-null object
dtypes: object(1)
memory usage: 208.0+ bytes
这证实了没有任何元素具有“true”None值。只有包含“None”的字符串。
另一个要注意的问题是:all(df.colx.index == range(df.colx.shape[0]))
只检查索引是否包含连续的数字,这对于colx的内容没有任何明示意义。
如何读取您的DataFrame
我猜想你是通过例如read_csv来读取DataFrame的,没有进行任何转换,所以 colx列是object(实际上是字符串)类型。
在这种情况下,如果第一个元素包含None(一个字符串),则尝试调用pd.to_datetime会失败,因为它无法转换为datetime。
应该怎么做
请尝试以下方法:
When reading the DataFrame, pass na_values=['None'] parameter.
It provides that elements containing None are not left as strings,
but are converted to NaNs.
Print the DataFrame (read from my limited source).
Instead of None (a string) there will be NaN - a special case of float.
Run df.info(). This time the printout will be:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 10 entries, 0 to 9
Data columns (total 1 columns):
colx 7 non-null object
dtypes: object(1)
memory usage: 208.0+ bytes
Note that there are only 7 non-null values, out of total 10,
so the 3 remaining are "true" None values, which Pandas prints as NaN.
Run pd.to_datetime(df.colx). This time there should be no error.
pandas
?如果版本小于0.25.0
,请尝试在pd.to_datetime
中指定cache=True
。我认为你在该列中遇到了pd.NaT
和None
都是空值的问题,这个问题已经在0.25版本中得到了解决。 - ALollzNone
和pd.NaT
,使用np.NaT
填充解决了问题。不过我的pandas版本是0.25.2。所以显然这仍然会引起问题。 - yatu