在Pandas(在Python中)将String列转换为Date的有效方法,但没有Timestamp

时间:2017-08-07 08:39:54

标签: string pandas date type-conversion timestamp

我有一个DataFrame,它包含两个String列strerror(errno)df['month']。我想通过合并df['year']df['date']列来创建新列month。我已成功使用下面的结构 -

year

其中by为df['date']=pd.to_datetime((df['month']+df['year']),format='%m%Y')

df['month'] = '08' and df['year']='1968'

这正是我想要的。

手头的问题:我的DataFrame有超过200,000行,我注意到有时候,我还会得到类似下面几行的Timestamp,我想避免这种情况 - < / p>

we get df['date']=1968-08-01

我使用1972-03-01 00:00:00 acessor解决了这个问题,可以用来操作系列,我使用下面的代码显式提取日期 -

.dt

问题解决了,只是第2行第1行花了 5次更多的时间。

问题:有没有什么方法可以将第1行调整为仅提供日期而不是时间戳?我确信这个简单的问题不能有这么低效的解决方案。我能以更节省时间和资源的方式解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

AFAIk我们没有from t in Application.Types where t.NameLike("Repository") select t dtype n Pandas,我们只有date,所以我们总是有时间部分。

即使Pandas显示:datetime,它也有时间部分:1968-08-01

演示:

00:00:00

如果你想要一个字符串表示,有一种更快的方法:

In [32]: df = pd.DataFrame(pd.to_datetime(['1968-08-01', '2017-08-01']), columns=['Date'])

In [33]: df
Out[33]:
        Date
0 1968-08-01
1 2017-08-01

In [34]: df['Date'].dt.time
Out[34]:
0    00:00:00
1    00:00:00
Name: Date, dtype: object

更新请注意,df['date'] = df['year'].astype(str) + '-' + df['month'].astype(str) + '-01' 会为您提供字符串表示形式:

.dt.date