Python熊猫系列故障日期时间
问题描述:
我认为这必须是一个熊猫的故障,熊猫系列(v.18.1和19太),如果我指定一个日期的系列,第一次它被添加为int (错误),第二次它被添加为日期时间(正确),我不明白原因。Python熊猫系列故障日期时间
例如,此代码:
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而不是日期时间。
有人可以帮我吗?, 非常感谢你提前, Javi。
答
原因是这个系列是一个'对象'类型,而熊猫DataFrame(或一个系列)的列是同类型的。你可以用D型(或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')
只有通用的“对象” D型可以容纳任何Python对象(在你的情况下,插入一个datetime.datetime对象在系列)。
此外,Pandas系列是基于Numpy Arrays,它不是混合类型,并且失败了使用Pandas DataFrames和Series或Numpy的计算优势的目的。
你可以用python list()来代替吗?或DataFrame()?
我不知道是什么原因导致此行为,但在向字符串列添加日期时应该小心。你知道你正在添加一行,而不是一列,对吗? – IanS
这听起来像一个bug,'系列'支持混合dtypes,所以它看起来像日期时间被强制为初始分配int,但然后覆盖相同的索引标签位置产生预期的行为。我会在[github]上发布一个问题(https://github.com/pandas-dev/pandas/issues) – EdChum
非常感谢EdChum – bracana