将熊猫数据框转换为日期时间

我有一个Pandas数据框,其每一列都以整数格式指定日期时间(年,月,日等)的元素。我想将这些单独的列连接到单个datetime对象中,根据the documentation,该对象是合法操作。但是经过一个令人沮丧的小时,我还没有弄清楚该如何做。例如,请参见以下最小示例:

import pandas as pd

df = pd.DataFrame(
    [[2011,5,3],[2014,9,13],[2022,1,1]],columns=("year","month","day")
)

datetime = df.apply(pd.to_datetime)

所需结果:

0 2011-05-03
1 2014-09-13
2 2022-01-01

实际结果:

                           year              ...                                        day
0 1970-01-01 00:00:00.000002011              ...              1970-01-01 00:00:00.000000003
1 1970-01-01 00:00:00.000002014              ...              1970-01-01 00:00:00.000000013
2 1970-01-01 00:00:00.000002022              ...              1970-01-01 00:00:00.000000001

有什么建议吗?

sunyylove 回答:将熊猫数据框转换为日期时间

pd.to_datetime将正确地解析列名称中的日期。另外,您可以拥有'hour''minute''second''millisecond''microsecond'和/或'nanosecond'列。

pd.to_datetime(df[['year','month','day']])
0   2011-05-03
1   2014-09-13
2   2022-01-01
dtype: datetime64[ns]

列命名对大小写不敏感,可以按任何顺序指定命名列。

df['MiNuTEs'] = 2
pd.to_datetime(df[['MiNuTEs','year','day']])

0   2011-05-03 00:02:00
1   2014-09-13 00:02:00
2   2022-01-01 00:02:00
dtype: datetime64[ns]
,

一种方法是联接列,然后使用pd.to_datetime进行解析:

df.astype(str).apply('/'.join,axis=1).apply(pd.to_datetime)

0   2011-05-03
1   2014-09-13
2   2022-01-01
dtype: datetime64[ns]
,

您可以这样做:

import pandas as pd

df = pd.DataFrame(
    [[2011,5,3],[2014,9,13],[2022,1,1]],columns=("year","month","day")
)

result = df.apply(lambda r: pd.Timestamp(year=r.year,month=r.month,day=r.day),axis=1)

print(result)

输出

0   2011-05-03
1   2014-09-13
2   2022-01-01
dtype: datetime64[ns]
本文链接:https://www.f2er.com/3079798.html

大家都在问