【发布时间】:2013-11-02 10:11:14
【问题描述】:
本着this answer 的精神,我尝试了以下方法将日期时间的DataFrame 列转换为自纪元以来的秒数列。
df['date'] = (df['date']+datetime.timedelta(hours=2)-datetime.datetime(1970,1,1))
df['date'].map(lambda td:td.total_seconds())
第二个命令导致以下我不明白的错误。对这里可能发生的事情有任何想法吗?我用 apply 替换了 map ,但这无济于事。
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-99-7123e823f995> in <module>()
----> 1 df['date'].map(lambda td:td.total_seconds())
/Users/cpd/.virtualenvs/py27-ipython+pandas/lib/python2.7/site-packages/pandas-0.12.0_937_gb55c790-py2.7-macosx-10.8-x86_64.egg/pandas/core/series.pyc in map(self, arg, na_action)
1932 return self._constructor(new_values, index=self.index).__finalize__(self)
1933 else:
-> 1934 mapped = map_f(values, arg)
1935 return self._constructor(mapped, index=self.index).__finalize__(self)
1936
/Users/cpd/.virtualenvs/py27-ipython+pandas/lib/python2.7/site-packages/pandas-0.12.0_937_gb55c790-py2.7-macosx-10.8-x86_64.egg/pandas/lib.so in pandas.lib.map_infer (pandas/lib.c:43628)()
<ipython-input-99-7123e823f995> in <lambda>(td)
----> 1 df['date'].map(lambda td:td.total_seconds())
AttributeError: 'float' object has no attribute 'total_seconds'
【问题讨论】:
-
看来“日期”列一开始可能不是 datetime64?
-
该列是否包含任何缺失值?缺失值通常会导致 pandas Series 被转换为浮点数,当您尝试将它们解释为日期时间时会导致奇怪。
-
@Abe 确实你是对的。原来在一些记录中有一些缺失的数据。不是我预期的……Ack。