Python Pandas Series 失败日期时间

7
我认为这一定是pandas的一个错误。在使用pandas Series(版本18.1和19)时,如果我给Series分配一个日期,第一次它会被添加为int类型(错误),第二次它会被添加为datetime类型(正确)。我无法理解原因。
例如,使用以下代码:
import datetime as dt
import pandas as pd
series = pd.Series(list('abc'))
date = dt.datetime(2016, 10, 30, 0, 0)
series["Date_column"] =date
print("The date is {} and the type is {}".format(series["Date_column"], type(series["Date_column"])))
series["Date_column"] =date
print("The date is {} and the type is {}".format(series["Date_column"], type(series["Date_column"])))

输出结果为:
The date is 1477785600000000000 and the type is <class 'int'>
The date is 2016-10-30 00:00:00 and the type is <class 'datetime.datetime'>

正如您所看到的,第一次它总是将值设置为int而不是datetime。

有人可以帮助我吗?非常感谢您的帮助,Javi。


1
我不知道是什么原因导致了这种行为,但是当你向字符串列添加日期时应该小心。你知道你正在添加一行而不是一列,对吧? - IanS
1
这对我来说像是一个 bug,Series 支持混合数据类型,所以看起来日期时间在初始赋值时被强制转换为整数,但是在相同的索引标签位置上进行覆盖赋值会产生预期的行为。我会在 github 上发布一个问题。 - EdChum
1个回答

1
这是因为Series是一种“对象”类型,而pandas DataFrame(或Series)的列都是同质的类型。您可以使用dtype(或DataFrame.dtypes)来检查这一点:
series = pd.Series(list('abc'))
series
Out[3]:
0    a
1    b
2    c
dtype: object

In [15]: date = dt.datetime(2016, 10, 30, 0, 0)
date
Out[15]: datetime.datetime(2016, 10, 30, 0, 0)

In [18]: print(date)
2016-10-30 00:00:00

In [17]: type(date)
Out[17]: datetime.datetime

In [19]: series["Date_column"] = date
In [20]: series

Out[20]:
0                                a
1                                b
2                                c
Date_column    1477785600000000000
dtype: object

In [22]: series.dtype

Out[22]: dtype('O')

只有通用的“object” dtype 可以容纳任何 Python 对象(在您的情况下将 datetime.datetime 对象插入 Series)。

此外,Pandas Series 基于 Numpy 数组,这些数组不是混合类型,并且破坏了使用 Pandas 数据帧和系列或 Numpy 的计算优势的目的。

您可以使用 python list() 或者 DataFrame() 吗?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接