【发布时间】:2018-02-02 03:09:58
【问题描述】:
场景:我有一个数据框,其中包含从 excel 工作表中检索到的多列。其中一些列是日期:一些只有日期 (yyyy:mm:dd),一些有日期和时间戳 (yyyy:mm:dd 00.00.000000)。
问题:当日期不是我的数据帧的索引时,如何从日期中删除时间戳?
我已经尝试过的: 从 SO(working with dates in pandas - remove unseen characters in datetime and convert to string 和 How to strip a pandas datetime of date, hours and seconds)的其他帖子中我发现:
pd.DatetimeIndex(dfST['timestamp']).date
和
strfitme (df['timestamp'].apply(lambda x: x.strftime('%Y-%m-%d'))
但是当它不是我的数据框的索引时,我似乎无法找到将它们直接用于所需列的方法。
【问题讨论】:
-
如果您已经转换为日期时间,则无需创建
DatetimeIndex。您可以使用 dt 访问器重新分配列:dfST['timestamp'] = dfST['timestamp'].dt.date -
各列的数据类型是什么?你说的
But I can't seem to find a way to use those directly to the wanted column when it is not the index of my dataframe.是什么意思 -
@AndrewL 刚试过,我得到:“AttributeError: Can only use .dt accessor with datetimelike values”
-
@MaartenFabré 我想它们是日期时间值。我的意思是当日期列是索引时,我的 OP 中的行有效,但不适用于我在数据框中的其他日期列。
标签: python pandas datetime dataframe