在 Python 中, Pandas :
g = pd.Series(dict(a = 5, b =datetime(2018, 1,1)))
g['datetime'] = pd.Timestamp('2018-01-02')
g
返回:
a 5
b 2018-01-01 00:00:00
datetime 1514851200000000000
dtype: object
任何人都知道为什么时间戳在这里转换为它的 int 值,以及如何避免这个问题并正确地将时间戳附加到系列?
最佳答案
我同意@MrE,他说:
I think it makes sense: 5 is not a datetime object, so pandas is parsing the data and find that you have both a number and a datetime object, and it parses both as 'object' string, because the dtype needs to be consistent across all data in the Series. The string representation of a datetime is the date string, not timestamp. When you then add to it, you can modify the dtype of a cell
我真的同意,它必须找到一个 dtype
并找到 int
,如果你删除 'a'
索引,它就会工作(这基本上是在检查以上内容是否属实):
g = pd.Series(dict(b =datetime(2018, 1,1)))
g['datetime'] = pd.Timestamp('2018-01-02')
print(g)
输出:
b 2018-01-01
datetime 2018-01-02
dtype: datetime64[ns]
原来如此。
解决问题:
只需在最后添加一行:
g['datetime']=pd.to_datetime(g['datetime'])
现在:
print(g)
是:
a 5
b 2018-01-01 00:00:00
datetime 2018-01-02 00:00:00
dtype: object
关于python - 使用 pandas 为系列分配时间戳值会创建一个 int 而不是,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50431592/