简体   繁体   English

使用 Pandas 重新格式化用户输入不一致的日期

[英]Using Pandas to reformat dates with inconsistent User inputs

I am trying to clean a spreadsheet of user-inputted data that includes a "birth_date" column.我正在尝试清理包含“birth_date”列的用户输入数据的电子表格。 The issue I am having is that the date formating ranges widely between users, including inputs without markers between the date, month, and year.我遇到的问题是用户之间的日期格式范围很广,包括在日期、月份和年份之间没有标记的输入。 I am having a hard time developing a formula that is intelligent enough to interpret such a wide range of inputs.我很难开发一个足够智能的公式来解释如此广泛的输入。 Here is a sample:这是一个示例:

1/6/46
7/28/99
11272000
11/28/78

Here is where I started:这是我开始的地方:

df['birth_date']=pd.to_datetime(df.birth_date)

This does not seem to make it past the first example, as it looks for a two-month format.这似乎并没有超过第一个例子,因为它寻找的是两个月的格式。 Can anyone help with this?有人能帮忙吗?

Your best bet is to check each input and give a consistent output.最好的办法是检查每个输入并给出一致的输出。 Assuming Month-Day-Year formats, you can use this function假设是 Month-Day-Year 格式,可以使用这个函数

import pandas as pd
import re

def fix_dates(dates):
    new = []
    for date in dates:
        chunks = re.split(r"[\/\.\-]", date)
        if len(chunks) == 3:
            m, d, y = map(lambda x: x.zfill(2), chunks)
            y = y[2:] if len(y) == 4 else y
            new.append(f"{m}/{d}/{y}")
        else:
            m = date[:2]
            d = date[2:4]
            y = date[4:]
            y = y[2:] if len(y) == 4 else y
            new.append(f"{m}/{d}/{y}")
    return new

inconsistent_dates = '1/6/46 7/28/99 11272000 11/28/78'.split(' ')

pd.to_datetime(pd.Series(fix_dates(inconsistent_dates)))

0   2046-01-06
1   1999-07-28
2   2000-11-27
3   1978-11-28
dtype: datetime64[ns]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM