pandas - 使用 to_datetime 将数据框对象转换为日期

标签 pandas datetime dataframe merge

我有一个看起来像这样的数据集:

    date        id
0   2014-01-01  11000929
1   2014-01-01  11000190
2   2014-01-01  11000216
3   2014-01-01  11000822
4   2014-01-01  11000971
5   2014-01-01  11000721
6   2014-01-01  11000970
7   2014-01-01  11000574
8   2014-01-01  11000967
9   2014-01-01  11000172
10  2014-01-01  11000208
11  2014-01-01  11000966
12  2014-01-01  11000344
13  2014-01-01  11000965
14  2014-01-01  11000935
15  2014-01-01  11000964
16  2014-01-01  11000741
17  2014-01-01  11000868
18  2014-01-01  11000035
19  2014-01-01  11000203
20  2014-01-02  11000574

如您所见,不同产品有很多重复的日期时间,我会将此表与另一个表合并,这需要我将当前和对象的日期列转换为 datetime64[ns]。

我试过了

df_date_id.date = pd.to_datetime(df_date_id.date)

但我最终遇到了错误:

TypeError: <class 'pandas._libs.tslibs.period.Period'> is not convertible to datetime

p.s:我要合并的表如下所示:

    date        id          score
0   2014-01-01  11000035    75
1   2014-01-02  11000035    84
2   2014-01-03  11000035    55

所以两个表的日期格式在我看来是一样的。 提前致谢。

最佳答案

我认为有必要使用 to_timestamp 将句点转换为日期时间:

df['date'] = df['date'].dt.to_timestamp()
print (df['date'].dtypes)
datetime64[ns]

另一种解决方案是将另一个 DataFrame 中的列转换为句点,例如:

df2['date'] = df2['date'].dt.to_period('d')

关于pandas - 使用 to_datetime 将数据框对象转换为日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53868872/

相关文章:

python - 搜索缺少的时间戳并在 python 中显示?

c# - 将日期时间格式化为特定格式

python - 找到列表中的三个单词在给定文档中同时出现的频率

pandas - python - 在python中连接两个df时,为什么会丢失有关使用np.hstack的索引和列标题信息?

python - 识别非连续零的索引值

Python将数据框中的列表转换为字符串

python - 带圆角的 Seaborn 或 Matplotlib 箱线图

c# - 有没有办法在 C# (ASP.NET MVC3) 中更改请求的时区?

ios - DateFormatter "HH"没有以 24 小时格式快速给出时间

python - 有条件聚合 Pandas DataFrame