【问题标题】:Easiest way to determine whether column in pandas Dataframe contains DATE or DATETIME information确定 pandas Dataframe 中的列是否包含 DATE 或 DATETIME 信息的最简单方法
【发布时间】:2020-10-05 21:50:15
【问题描述】:

我有以下 DF:

  col1         col2
1 2017-01-03   2018-03-30 08:01:32
2 2017-01-04   2018-03-30 08:02:32

如果我执行df.dtypes,我会得到以下输出:

col1    datetime64[ns]
col2    datetime64[ns]
dtype: object

然而col1 仅包含日期信息 (DATE),而 col2 包含日期和时间信息 (DATETIME)。

确定列是否包含 DATE 或 DATETIME 信息的最简单方法是什么?

数据生成:

import pandas as pd

# Generate the df
col1 = ["2017-01-03", "2017-01-04"]
col2 = ["2018-03-30 08:01:32", "2018-03-30 08:02:32"]

df = pd.DataFrame({"col1": col1, "col2": col2})

df["col1"] = pd.to_datetime(df["col1"])
df["col2"] = pd.to_datetime(df["col2"])

【问题讨论】:

    标签: python pandas dataframe datetime


    【解决方案1】:

    你可以试试这个:

    def col_has_time(col):
        dt = pd.to_datetime(df[col])
        return (dt.hour == 0).all()
    

    【讨论】:

    • 逻辑类似于我上面介绍的函数...您的函数检查所有时间戳的小时属性是否具有相同的值(即零),我的函数检查所有日期是否相同如果你切断了时间信息(简化)。对我来说,这两种方式都是间接的。我希望有一个内置的熊猫功能(或类似的东西)
    【解决方案2】:

    根据this SO Question,以下函数可以完成这项工作:

    def check_col(col):
        try:
            dt = pd.to_datetime(df[col])
            if (dt.dt.floor('d') == dt).all():
                return('Its a DATE field')
            else:
                return('Its a DATETIME field')
        except:
            return("could not parse to pandas datetime")
    

    但是,没有更直接的方法吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-19
      • 1970-01-01
      • 1970-01-01
      • 2022-09-24
      • 2014-02-14
      • 2022-08-20
      • 1970-01-01
      相关资源
      最近更新 更多