2017-08-24 333 views
1

场景:我有一个数据框,其中包含从excel工作表中检索到的多个列。其中一些列吃了日期:一些只有日期(yyyy:mm:dd),另一些有日期和时间戳(yyyy:mm:dd 00.00.000000)。从pandas数据框中的日期时间删除时间戳

问题:如何从日期中删除时间戳,这些日期不是我数据框的索引?

我已经尝试过:从这里其他职位的SO(working with dates in pandas - remove unseen characters in datetime and convert to stringHow 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')) 

但我似乎无法找到一种方法当它不是我的数据框的索引时,直接使用它们到想要的列。

+2

如果您已经转换为DATETIME你不会需要创建一个'DatetimeIndex'。您可以使用dt访问器重新分配列:'dfST ['timestamp'] = dfST ['timestamp']。dt.date' –

+0

相应列的dtype是什么?你是什​​么意思'但我似乎无法找到一种方式来使用这些直接到想要的列,当它不是我的数据框的索引。' –

+0

@AndrewL刚刚尝试过,我得到:“AttributeError:Can只使用.dt访问器与datetimelike值“ – DGMS89

回答

1

你可以做到以下几点:

dfST['timestamp'] = pd.to_datetime(dfST['timestamp']) 

to_datetime()会推断日期列的格式。如果该列包含非日期值,则还可以传递errors='coerce'

完成上述后,您就可以创建只包含日期值的新列:

dfST['new_date_column'] = dfST['timestamp'].dt.date 
+1

Coerce做了诡计,非常感谢。 – DGMS89