如何仅更改 Pandas 中某些行的日期时间格式?

发布于 2025-01-13 17:41:10 字数 664 浏览 0 评论 0原文

我有一个数据框,其中有一些列。其中之一是日期,但有些日期的格式为 dd-MMM-YY(例如:03-May-2022),有些日期的格式为 dd-mm-yy(例如:03-05-2022)。如何将列中的所有日期更改为一种格式(例如:dd-mm-yy)?

初始数据框:

序列日期
023-05-2022
114-Mar-2022
229-02-2020

所需输出:

序列日期
023-05-2022
114 -03-2022
229-02-2020

I have a dataframe in which there are some columns. One of them is Date but some dates are in the format of dd-MMM-YY (eg: 03-May-2022) and some are in the format dd-mm-yy(eg: 03-05-2022). How do I change all the dates in the column to one format(eg: dd-mm-yy)?

Initial Dataframe:

SerialDate
023-05-2022
114-Mar-2022
229-02-2020

Required Output:

SerialDate
023-05-2022
114-03-2022
229-02-2020

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

马蹄踏│碎落叶 2025-01-20 17:41:10

我可以想到一种解决方案,根据日期字符串的长度处理两种不同的情况:

def format_date(date):
    reformatter = {
        "Jan": "01",
        "Feb": "02",
        "Mar": "03",
        ...
        "Dec": "12"

    }
    if len(date) == 10:
        return date
    else:
        return date[:4] + reformatter[date[3:6]] + date[6:]

df["Date"].apply(lambda x: format_date(x))

I can think of one solution where you handle the two different cases based on length of the date string:

def format_date(date):
    reformatter = {
        "Jan": "01",
        "Feb": "02",
        "Mar": "03",
        ...
        "Dec": "12"

    }
    if len(date) == 10:
        return date
    else:
        return date[:4] + reformatter[date[3:6]] + date[6:]

df["Date"].apply(lambda x: format_date(x))
爱情眠于流年 2025-01-20 17:41:10

您可以尝试使用自动日期解析:

df['Date'] = (pd.to_datetime(df['Date'], infer_datetime_format=True)
                .dt.strftime('%d-%m-%Y')
              )

或者使用 str.replace

from calendar import month_abbr

d = dict(zip(month_abbr, [f'{i:02d}' for i in range(13)]))

df['Date'] = df['Date'].str.replace(r'[A-Z][a-z]+', lambda x: d.get(x.group(), x), regex=True)

输出:

   Serial        Date
0       0  23-05-2022
1       1  14-03-2022
2       2  29-02-2020

You can try to use automatic date parsing:

df['Date'] = (pd.to_datetime(df['Date'], infer_datetime_format=True)
                .dt.strftime('%d-%m-%Y')
              )

Or, using str.replace:

from calendar import month_abbr

d = dict(zip(month_abbr, [f'{i:02d}' for i in range(13)]))

df['Date'] = df['Date'].str.replace(r'[A-Z][a-z]+', lambda x: d.get(x.group(), x), regex=True)

Output:

   Serial        Date
0       0  23-05-2022
1       1  14-03-2022
2       2  29-02-2020
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文