Python Pandas Series失败日期时间

bra*_*ana 7 python datetime series pandas

我认为这必须是大熊猫的失败,有一个大熊猫系列(也是第18.1和19节),如果我给系列分配一个日期,第一次添加为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"])))
Run Code Online (Sandbox Code Playgroud)

输出是:

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'>
Run Code Online (Sandbox Code Playgroud)

如您所见,它第一次始终将值设置为int而不是datetime.

有人可以帮助我吗?非常感谢你,Javi.

rat*_*het 1

原因是系列是“对象”类型,并且 pandas DataFrame(或系列)的列是同质类型。您可以使用 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')
Run Code Online (Sandbox Code Playgroud)

只有通用的“object”dtype 可以保存任何 python 对象(在您的情况下将 datetime.datetime 对象插入到 Series 中)。

此外,Pandas Series 基于 Numpy 数组,它们不是混合类型,违背了利用 Pandas DataFrames 和 Series 或 Numpy 的计算优势的目的。

你能用 python list() 代替吗?或 DataFrame()?