gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 00:25:41 25 4
gpt4 key购买 nike

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

    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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com