【问题标题】:Flexibly align date formats in pandas灵活对齐 pandas 中的日期格式
【发布时间】:2022-01-18 20:59:21
【问题描述】:

我有一个包含许多列的 df。对于每一列,我都会确定类型,并得出见解。 例如,我标识为日期的列(使用parse(string, fuzzy=fuzzy))被发送到下面的函数:

def find_date_insights(df: pd.DataFrame, col: str) -> str:
    date_df = pd.to_datetime(df[col])
    return f"{date_df.min()} - {date_df.max()}"

当我在列中混合使用日期格式时,问题就开始了,主要是当空值被标记为破折号 (-) 以及当一些值是字符串格式 (2021-01-01) 而有些是数字时格式 (44197)。我尝试添加, errors='coerce',但随后的值显然不是被视为日期的日期。如果我错误地识别了字段类型,我确实希望运行失败。 因此,我尝试通过以下方式解释上述具体情况:

def find_date_insights(df: pd.DataFrame, col: str) -> str:
    try:
        date_df = pd.to_datetime(df[col])
    except:
        date_df[col] = (datetime.utcfromtimestamp(0) + timedelta(df[col].astype(int))).strftime("%Y-%m-%d")
        date_df = pd.to_datetime(date_df[col])
    return f"{date_df.min()} - {date_df.max()}"

但现在日期列在合法日期上出现错误... 我几乎迷路了,希望您能提供帮助。 谢谢!

您可以在下面找到一个方便的脚本来玩:

import pandas as pd
from datetime import datetime, timedelta
import numpy as np


def find_date_insights(df: pd.DataFrame, col: str) -> str:
    date_df = df[col]
    date_df[col] = np.where(df[col].astype(str) == '-', '', df[col].astype(str))
    try:
        date_df = pd.to_datetime(date_df[col])
    except:
        print('dang')
        date_df[col] = (datetime.utcfromtimestamp(0) + timedelta(df[col].astype(int))).strftime("%Y-%m-%d")
        date_df = pd.to_datetime(date_df[col])

    return f"{date_df.min()} - {date_df.max()}"


if __name__ == '__main__':
     d = {'bad_date': ["44198", "4952837597","32000"],
          'good_date': ["-", "2021-01-01", "44197"],
          'clear_date': ["2021-01-01", "2021-02-01", "2021-01-03"]}
     df = pd.DataFrame(data=d)
     for c in df.columns:
          try:
               print(find_date_insights(df,c))
          except Exception as e:
               print(c+": "+str(e))

我预计bad_date 会失败,而其他两个会成功。

【问题讨论】:

    标签: python pandas datetime


    【解决方案1】:

    我最终缩小了问题定义的范围,将其发布在这里: Converting pandas column to date, with many type of dates 并使用提供的答案。谢谢!

    【讨论】:

      猜你喜欢
      • 2020-06-15
      • 1970-01-01
      • 2020-04-11
      • 2013-03-02
      • 1970-01-01
      • 2021-11-04
      • 1970-01-01
      • 2018-02-20
      • 1970-01-01
      相关资源
      最近更新 更多